Python List

Python List is used to hold numbers of object in python in given order and also allow users to add, update, search and remove objects from list.

Initialize List

To create a list use a square bracket.

Syntax:

lst = []
lst = [object1,object2,...]

#built in list types methods
lst = list()

#from existing list sequence
lst = list[seq]

#using iterator and function
lst = list(fun(val) for val in list)


Examples:

lst = []
lst = [object1,object2,...]

Access List

lst1 = ['maths', 'physics','chemistry'];
lst2 = [1990,1991,1992,1993];

print(lst1[0])
#maths

print(lst1[2])
#chemistry

print(lst2[1:3])
#[1991,1992]

Iterate Over List

Many time user required to iterate over all list element with index or index is not necessary. Below are the example for how to iterate over python list.

for sub in lst1:
    print(sub)

for i in range(len(lst1)):
    print(lst1[i])

Add / Update / Delete in List

Examples to add, update or delete element from python list:
#add to list
lst1 = ['maths', 'physics','chemistry'];
lst1.append('english')
print(lst1)
#['maths', 'physics', 'chemistry', 'english']

#update in list
lst1[0] = 'biology'
print(lst1)
#['biology', 'physics', 'chemistry', 'english']

#delete from list
del lst1[3]
print(lst1)
#['biology', 'physics', 'chemistry']

Search Element from List

Using in keyword user can check object is present in list or not, to get index of search element use index method. For Above list,

val = 'physics'
if val in lst1:
	print(lst1.index(val))

Sorting

The sort method sorts a list in place.

lst1.sort()

To get a sorted copy, use the built-in sorted function:

out = sorted(lst1)

More Details On List

Leave a Reply

Your email address will not be published. Required fields are marked *