If we want to represent a group of individual objects as a single entity where insertion order preserved and duplicates are allowed, then we should go for List.
- insertion order preserved.
- duplicate objects are allowed
- heterogeneous objects are allowed.
- List is dynamic because based on our requirement we can increase the size and decrease the size.
- In List the elements will be placed within square brackets and with comma seperator.
We can differentiate duplicate elements by using index and we can preserve insertion order by using index. Hence index will play very important role.
Python supports both positive and negative indexes. +ve index means from left to right where as negative index means right to left.
[10,”A”,”B”,20, 30, 10]
List objects are mutable.i.e. we can change the content.
Creation of List Objects:
We can create empty list object as follows
list=[]
print(list)
print(type(list))
[]
<class 'list'>
If we know elements already then we can create list as follows list=[10,20,30,40]
With dynamic input:
list=eval(input(“Enter List:”))
print(list)
print(type(list))
D:\Python_classes>py test.py
Enter List:[10,20,30,40]
[10, 20, 30, 40]
With list() function:
l=list(range(0,10,2))
print(l)
print(type(l))
D:\Python_classes>py test.py
[0, 2, 4, 6, 8]
Ex:
s=”seedgroup”
l=list(s)
print(l)
D:\Python_classes>py test.py
[‘s’,’e’,’e’,’d’,’g’,’r’,’o’,’u’,’p’]
with split() function:
s=”Learning Python is very very easy !!!”
l=s.split()
print(l)
print(type(l))
D:\Python_classes>py test.py
[‘Learning’, ‘Python’, ‘is’, ‘very’, ‘very’, ‘easy’, ‘!!!’]
Note: Sometimes we can take list inside another list, such type of lists are called nested lists. [10,20,[30,40]]
Accessing elements of List:
We can access elements of the list either by using index or by using slice operator(:)
By using index:
- List follows zero based index. ie index of first element is zero.
- List supports both +ve and -ve indexes.
- +ve index meant for Left to Right
- -ve index meant for Right to Left
list=[10,20,30,40]
print(list[0]) ==>10
print(list[-1]) ==>40
print(list[10]) ==>IndexError: list index out of range
By using slice operator:
Syntax: list2 = list1[start:stop:step] start ==>it indicates the index where slice has to start default value is 0 stop ===>It indicates the index where slice has to end default value is max allowed index of list ie length of the list step ==>increment
Ex:
n=[1,2,3,4,5,6,7,8,9,10]
print(n[2:7:2])
print(n[4::2])
print(n[3:7])
print(n[8:2:-2])
print(n[4:100])
Output
D:\Python_classes>py test.py
[3, 5, 7]
[5, 7, 9]
[4, 5, 6, 7]
[9, 7, 5]
[5, 6, 7, 8, 9, 10]
List vs mutability:
Once we creates a List object,we can modify its content. Hence List objects are mutable.
Ex:
n=[10,20,30,40]
print(n)
n[1]=777
print(n)
D:\Python_classes>py test.py
[10, 20, 30, 40]
[10, 777, 30, 40]
Traversing the elements of List:
The sequential access of each element in the list is called traversal.
By using while loop:
n=[0,1,2,3,4,5,6,7,8,9,10]
i=0
while i<len(n):
print(n[i])
i=i+1
D:\Python_classes>py test.py
0
1
2
3
4
5
6
7
8
9
10
By using for loop:
n=[0,1,2,3,4,5,6,7,8,9,10]
for n1 in n:
print(n1)
D:\Python_classes>py test.py
0
1
2
3
4
5
6
7
8
9
10
To display only even numbers:
n=[0,1,2,3,4,5,6,7,8,9,10]
for n1 in n:
if n1%2==0:
print(n1)
D:\Python_classes>py test.py
0
2
4
6
8
10
len():
returns the number of elements present in the list
Ex: n=[10,20,30,40]
print(len(n))==>4
count():
It returns the number of occurrences of specified item in the list
n=[1,2,2,2,2,3,3] print(n.count(1)) print(n.count(2)) print(n.count(3)) print(n.count(4)) Output D:\Python_classes>py test.py 1 4 2 0
index() function:
returns the index of first occurrence of the specified item.
Ex:
n=[1,2,2,2,2,3,3]
print(n.index(1)) ==>0
print(n.index(2)) ==>1
print(n.index(3)) ==>5
print(n.index(4)) ==>ValueError: 4 is not in list
Note: If the specified element not present in the list then we will get ValueError. Hence before index() method we have to check whether item present in the list or not by using in operator.
print( 4 in n)==>False
Manipulating elements of List:
append() function:
We can use append() function to add item at the end of the list.
Ex:
list=[]
list.append(“A”)
list.append(“B”)
list.append(“C”)
print(list)
D:\Python_classes>py test.py
[‘A’, ‘B’, ‘C’]
Ex: To add all elements to list up to 100 which are divisible by 10
list=[]
for i in range(101):
if i%10==0:
list.append(i)
print(list)
D:\Python_classes>py test.py
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
insert() function:
To insert item at specified index position
n=[1,2,3,4,5]
n.insert(1,888)
print(n)
D:\Python_classes>py test.py
[1, 888, 2, 3, 4, 5]
Ex:
n=[1,2,3,4,5]
n.insert(10,777)
n.insert(-10,999)
print(n)
D:\Python_classes>py test.py
[999, 1, 2, 3, 4, 5, 777]
Note:
- If the specified index is greater than max index then element will be inserted at last position.
- If the specified index is smaller than min index then element will be inserted at first position.
Differences between append() and insert()
append() | insert() |
In List when we add any element it will | In List we can insert any element in |
come in last i.e. it will be last element. | particular index number |
extend() function:
To add all items of one list to another list
l1.extend(l2)
all items present in l2 will be added to l1
Ex:
order1=[“Delhi”,”Mumbai”,”Chennai”]
order2=[“Agra”,”Kanpur”,”Lucknow”]
order1.extend(order2)
print(order1)
D:\Python_classes>py test.py
[‘Delhi’, ‘Mumbai’, ‘Chennai’, ‘Agra’, ‘Kanpur’, ‘Lucknow’]
Ex:
order=[“Chicken”,”Mutton”,”Fish”]
order.extend(“Mushroom”)
print(order)
D:\Python_classes>py test.py
[‘Chicken’, ‘Mutton’, ‘Fish’, ‘M’, ‘u’, ‘s’, ‘h’, ‘r’, ‘o’, ‘o’, ‘m’]
remove() function:
We can use this function to remove specified item from the list.If the item present multiple times then only first occurrence will be removed.
n=[10,20,10,30]
n.remove(10)
print(n)
D:\Python_classes>py test.py
[20, 10, 30]
If the specified item not present in list then we will get ValueError
n=[10,20,10,30]
n.remove(40)
print(n)
ValueError: list.remove(x): x not in list
Note: Hence before using remove() method first we have to check specified element present in the list or not by using in operator.
pop() function:
- It removes and returns the last element of the list.
- This is only function which manipulates list and returns some element.
Ex:
n=[10,20,30,40]
print(n.pop())
print(n.pop())
print(n)
D:\Python_classes>py test.py
40
30
[10, 20]
If the list is empty then pop() function raises IndexError
Ex:
n=[]
print(n.pop()) ==>IndexError: pop from empty list
Note:
- pop() is the only function which manipulates the list and returns some value
- In general we can use append() and pop() functions to implement stack data structure by using list, which follows LIFO(Last In First Out) order.
In general we can use pop() function to remove last element of the list. But we can use to remove elements based on index.
n.pop(index)===>To remove and return element present at specified index. n.pop()==>To remove and return last element of the list
n=[10,20,30,40,50,60]
print(n.pop()) #60
print(n.pop(1)) #20
print(n.pop(10)) ==>IndexError: pop index out of range
Note:
- List objects are dynamic. i.e based on our requirement we can increase and decrease the size.
append(),insert() ,extend() ===>for increasing the size/growable nature remove(), pop() ======>for decreasing the size /shrinking nature
Ordering elements of List:
reverse():
We can use to reverse() order of elements of list.
n=[10,20,30,40]
n.reverse()
print(n)
D:\Python_classes>py test.py
[40, 30, 20, 10]
sort() function:
In list by default insertion order is preserved. If want to sort the elements of list according to default natural sorting order then we should go for sort() method.
For numbers ==>default natural sorting order is Ascending Order For Strings ==>default natural sorting order is Alphabetical Order
n=[20,5,15,10,0]
n.sort()
print(n) #[0,5,10,15,20]
s=[“Dog”,”Banana”,”Cat”,”Apple”]
s.sort()
print(s) #[‘Apple’,’Banana’,’Cat’,’Dog’]
Note: To use sort() function, compulsory list should contain only homogeneous elements. Otherwise we will get TypeError
Ex:
n=[20,10,”A”,”B”]
n.sort()
print(n)
TypeError: ‘<‘ not supported between instances of ‘str’ and ‘int’
Note:
- In Python 2 if List contains both numbers and Strings then sort() function first sort numbers followed by strings
n=[20,”B”,10,”A”]
n.sort()
print(n) #[10,20,’A’,’B’]
But in Python 3 it is invalid.
To sort in reverse of default natural sorting order:
We can sort according to reverse of default natural sorting order by using reverse=True argument.
Ex:
n=[40,10,30,20]
n.sort()
print(n) ==>[10,20,30,40]
n.sort(reverse=True)
print(n) ===>[40,30,20,10]
n.sort(reverse=False)
print(n) ==>[10,20,30,40]
Aliasing and Cloning of List objects:
The process of giving another reference variable to the existing list is called aliasing.
Ex:
x=[10,20,30,40]
y=x # 10 20 30 40
print(id(x)) X
print(id(y)) Y
By using slice operator:
x=[10,20,30,40]
y=x[:]
y[1]=777
print(x) ==>[10,20,30,40]
print(y) ==>[10,777,30,40]
By using copy() function:
x=[10,20,30,40]
y=x.copy()
y[1]=777
print(x) ==>[10,20,30,40]
print(y) ==>[10,777,30,40]
Using Mathematical operators for List Objects:
We can use + and * operators for List objects.
Concatenation operator(+):
We can use + to concatenate 2 lists into a single list
a=[10,20,30]
b=[40,50,60]
c=a+b
print(c) ==>[10,20,30,40,50,60]
Note: To use + operator compulsory both arguments should be list objects,otherwise we will get TypeError.
Ex:
c=a+40 ==>TypeError: can only concatenate list (not “int”) to list
c=a+[40] ==>valid
Repetition Operator(*):
We can use repetition operator * to repeat elements of list specified number of times
Ex:
x=[10,20,30]
y=x*3
print(y) ==>[10,20,30,10,20,30,10,20,30]
Comparing List objects
We can use comparison operators for List objects.
Ex:
x=[“Dog”,”Cat”,”Rat”]
y=[“Dog”,”Cat”,”Rat”]
z=[“DOG”,”CAT”,”RAT”]
print(x==y) True
print(x==z) False
print(x != z) True
Note:
- Whenever we are using comparison operators(==,!=) for List objects then the following should be considered
- The number of elements
- The order of elements
- The content of elements (case sensitive)
Note:
Whenever we are using relational operators(<,<=,>,>=) between List objects, only first element comparison will be performed.
Ex:
x=[50,20,30]
y=[40,50,60,100,200]
print(x>y) True
print(x>=y) True
print(x<y) False
print(x<=y) False
Membership operators:
We can check whether element is a member of the list or not by using memebership operators.
in operator
not in operator
Ex:
n=[10,20,30,40]
print (10 in n)
print (10 not in n)
print (50 in n)
print (50 not in n)
Output
True
False
False
True
clear() function:
We can use clear() function to remove all elements of List.
Ex:
n=[10,20,30,40]
print(n)
n.clear()
print(n)
Output
D:\Python_classes>py test.py
[10, 20, 30, 40]
[]
Nested Lists:
Sometimes we can take one list inside another list. Such type of lists are called nested lists.
Ex:
n=[10,20,[30,40]]
print(n)
print(n[0])
print(n[2])
print(n[2][0])
print(n[2][1])
Output
D:\Python_classes>py test.py
[10, 20, [30, 40]]
10
[30, 40]
30
40
Note:
We can access nested list elements by using index just like accessing multi-dimensional array elements.
Nested List as Matrix:
In Python we can represent matrix by using nested lists.
n=[[10,20,30],[40,50,60],[70,80,90]]
print(n)
print(“Elements by Row wise:”)
for r in n:
print(r)
print(“Elements by Matrix style:”)
for i in range(len(n)):
for j in range(len(n[i])):
print(n[i][j],end=’ ‘)
print()
Output
D:\Python_classes>py test.py
[[10, 20, 30], [40, 50, 60], [70, 80, 90]]
Elements by Row wise:
[10, 20, 30]
[40, 50, 60]
[70, 80, 90]
Elements by Matrix style:
10 20 30
40 50 60
70 80 90
List Comprehensions:
It is very easy and compact way of creating list objects from any iterable objects(like list,tuple,dictionary,range etc.) based on some condition.
Syntax: list=[expression for item in list if condition]
Ex:
s=[ xx for x in range(1,11)] print(s) v=[2*x for x in range(1,6)]
print(v)
m=[x for x in s if x%2==0]
print(m)
Output
D:\Python_classes>py test.py
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
[2, 4, 8, 16, 32]
[4, 16, 36, 64, 100]