Creating and Accessing Lists With Python Programing - Coderz*United

Creating and Accessing Lists With Python Programing



Sequences in Python 

A sequence is a data type that represents a group of elements. The purpose of any sequence is to store and process a group of elements. In Python, strings, lists and tuples are sequences. All sequences allow some common operations like indexing and slicing.

Lists 

A list is a container which consists of a group of elements or items. The elements can be of any valid data type. 

Creating Lists 

We create a list by embedding the elements inside a pair of square brackets [ ]. The elements in the list should be separated by a comma (,)

E.g. L=[1,2,3,4] 

L2=[‘Sitara’,24,’F’,56.7,98.7,45.7,89.9] 

Empty List 

A list without any elements is called an empty list. An empty list is created by simply using empty square brackets: L=[ ] 


Python Lists are mutable 

In Python lists, elements can be changed in place, that is, changes can be made to individual elements of the list. Lists and Dictionaries are mutable types. All other data types of Python are immutable. 


Creating Lists using list() function 

Using the built-in function list(), a list can be created from any type of sequence object like strings, tuples or lists. 

The argument passed to list() needs to be iterable. 

list() 

Out[1]: [ ] 

L = list('hello'

print(L)

Out[1]:['h', 'e', 'l', 'l', 'o'] 

L = list(1,2,3,4)) 

print(L)

Out[1]: [1, 2, 3, 4] 

L = list([1,2,3,4]) 

print(L) 

Out[1]:[1, 2, 3, 4] 

L = list(12345) 

print(L)


Traceback (most recent call last): File "", line 1, in l=list(12345) 

TypeError: 'int' object is not iterable 

Creating Lists using eval() function 

L = eval(input("Enter: ")) 

Enter:[1,2,3,4] 

print(L)

Out[1]: [1, 2, 3, 4]

eval() evaluate 

L = eval('12134'

print(L)

Out[1]: 12134 

type(L)  

Out[2]: int 

L = eval('12134.90')

print(L)

Out[3]: 12134.9 

type(L

Out[4]: float 

Accessing Lists 

As lists are mutable or editable sequences, we can access and manipulate individual elements of a list. 

In strings we could access individual elements but cannot manipulate elements in a list. 

s='abc' 

print(s[0]) 

Out[1]: 'a' 

s[0]='g' 

TypeError: 'str' object does not support item assignment 


L=[1,2,3,4,5,6

L[0]=9 

print(L) 

Out[2]:[9, 2, 3, 4, 5, 6]