Chapter 2 List
Chapter 2 List
Introduction
Like a String, list also is sequence data type. It is an ordered set of values enclosed in
square brackets []. Values in the list can be modified, i.e. it is mutable. As it is set of
values, we can use index in square brackets [] to identify a value belonging to it. The
values that make up a list are called its elements, and they can be of any type.
We can also say that list data type is a container that holds a number of elements in a
given order. For accessing an element of the list, indexing is used.
0, -size 1st
1, -size +1 2nd
193
2, -size +2 3rd
.
.
.
Please note that in the above example size is the total number of elements in the list.
You will study about Nested lists in later parts of the chapter.
To change the value of element of list, we access the element & assign the new value.
Example
>>>print L1
>>> L1 [2] = 5
[1, 2, 5, 4]
Here, 3rd element of the list (accessed using index value 2) is given a new value, so
instead of 3 it will be 5.
194
L1 0 1 L2 0 Delhi L3
1 2 1 Chennai
2 3 2 Mumbai
3 4
Note: List index works the same way as String index, which is:
An integer value/expression can be used as index.
An Index Error appears, if you try and access element that does not exist in the
list.
An index can have a negative value, in that case counting happens from the end
of the list.
Creating a list
List can be created in many ways:
Example
L5=L1 [:]
>>>print L5
L6 = L1 [0:2]
>>>print L6
Example
>>>n = 5
195
>>>l = range(n)
>>>print l
[0, 1, 2, 3, 4]
Example
>>> print S
In mathematical terms, S can be defined as S = {x2 for: x in (0.....9)}. So, we can say
that list comprehension is short-hand for creating list.
Example
>>> A = [3, 4, 5]
Here B will be created with the help of A and its each element will be thrice of
element of A.
>>> print B
>>>B = [ ]
>>>for i in A
B. append (i*3)
Example
>>> print B
>>>C = [i for i in S if i % 2 = = 0]
196
>>>print C
Example
>>>l = list ( )
>>>print l
[ ] # empty list
Or
L = list (sequence)
Example
>>>print L
[1, 2, 3, 4]
A single new list is created every time, you execute [ ]. We have created many
different lists each using [ ]. But if a list is assigned to another variable, a new list
is not created.
i) A=B=[ ]
Example
>>> print A, B
ii) A=[]
B=A
197
Example
>>> A = [1, 2, 3]
>>> B = A
>>> print A, B
[1, 2, 3] [1, 2, 3]
List Slices
Slice operator works on list also. We know that a slice of a list is its sub-list. For creating
a list slice, we use
[n:m] operator.
>>>print L5 [0]
>>>print L5 [2]
[6, 7, 8]
as the 3rd element of this list is a list. To access a value from this sub-list, we will use
This will return the part of the list from nth element to mth element, including the first
element but excluding the last element. So the resultant list will have m-n elements in it.
>>> L1 [1:2]
will give
[2]
198
Slices are treated as boundaries, and the result will contain all the elements between
boundaries.
Where start, stop & step- all three are optional. If you omit first index, slice starts from
Example
>>>L2 [0:2]
Example
>>>list [4:] # will produce a list containing all the elements from 5th position
till end
[50, 60]
Example
>>>list [:3]
>>>list [:]
Example
60
199
Note: Since lists are mutable, it is often recommended to make a copy of it before
performing operation that change a list.
Traversing a List
Let us visit each element (traverse the list) of the list to display them on screen. This can
be done in many ways:
(i) i=0
while i < 4:
print L1 [i],
i+=1
1254
print i,
(iii) i=0
print L1 [i],
i+=1
OR
i= 0
L = len (L1)
while i < L :
print L1 [i],
i+=1
200
Here len( ) function is used to get the length of list L1. As length of L1 is 4, i will take
value from 0 to 3.
print L1 [i],
Using 2nd way for transversal will only allow us to print the list, but other ways can also
be used to write or update the element of the list.
In 4th way, range ( ) function is used to generate, indices from 0 to len -1; with each
iteration i gets the index of next element and values of list are printed.
Example
for i in [ ]:
print i
i=1
print L1 [-i],
i += 1
In this case, Python will add the length of the list to index and then return the
index value and accesses the desired element. In this loop execution for a positive
-i] will result into L1 [len (L1)-i] for i=1, L1 [4-1] will be printed. So
resultant of the loop will be 4 5 2.
201
L1. append (70)
This will add 70 to the list at the end, so now 70 will be the 5th element of the list, as it
already have 4 elements.
>>> print L1
[1, 2, 5, 4, 70]
Example
>>>print L4
Using append ( ), only one element at a time can be added. For adding more than one
element, extend ( ) method can be used, this can also be used to add elements of another
list to the existing one.
Example
>>> print L1
will
>>>print A
Example
>>>B.extend (c)
>>>print B
202
Remember:
Example
>>> print L1
will produce
Example
>>>print A
will produce
[10, 100]
As lists are sequences, they support many operations of strings. For example, operator +
& * results in concatenation & repetition of lists. Use of these operators generate a new
list.
Example
>>> a= L1+L2
will produce a 3rd list a containing elements from L1 & then L2. a will contain
203
Example
[1, 2, 3, 4, 5, 6]
Example
>>> b = L1*2
>>> print b
[[1, 10, 20, 4, 70, 100, 90, 80, 50, 1, 10, 20, 4, 70, 100, 90, 80, 50]
Example
>>> [
It is important to know that operator in lists expects the same type of sequence on
both the sides otherwise you get a type error.
If you want to concatenate a list and string, either you have to convert the list to string
or string to list.
Example
, 12]
34 ) or >>>
Deleting Elements
It is possible to delete/remove element(s) from the list. There are many ways of doing
so:
(ii) If the element is known, not the index, remove ( ) can be used.
(iii) To remove more than one element, del ( ) with list slice can be used.
204
Let us study all the above methods in details:
Pop ( )
It removes the element from the specified index, and also return the element which was
removed.
List.pop ([index])
Example
>>> print L1
>>> print a
>>>L1.pop ( )
50
del removes the specified element from the list, but does not return the deleted
value.
>>> print L1
remove ( )
In case, we know the element to be deleted not the index, of the element, then remove (
) can be used.
205
>>> print L1
Examples
>>>print L1
[1, 5, 80]
will remove 2nd and 3rd element from the list. As we know that slice selects all the
elements up to 2nd index but not the 2nd index element. So 4th element will remain in the
list.
>>> L5 [1:2] = [ ]
>>>print L5
Note:
(i) All the methods, modify the list, after deletions.
(ii) If an out of range index is provided with del ( ) and pop ( ), the code will result
in to run-time error.
(iii) del can be used with negative index value also.
206
Its syntax is
Index specifies the position (starting from 0) where the element is to be inserted. Item is
the element to be inserted in the list. Length of list changes after insert operation.
Example
>>>print L1
will produce
Note: If the index specified is greater then len (list) the object is inserted in the last
and if index is less than zero, the object is inserted at the beginning.
>>>print L1
will produce
reverse ( )
This method can be used to reverse the elements of the list in place
list.reverse ( )
Method does not return anything as the reversed list is stored in the same variable.
Example
>>> L1.reverse ( )
207
>>> print L1
will produce
>>>L1 [: : -1]
As this slices the whole sequence with the step of -1 i.e. in reverse order.
sort ( )
For arranging elements in an order Python provides a method sort ( ) and a function
sorted ( ). sort ( ) modifies the list in place and sorted ( ) returns a new sorted list.
Parameters mentioned in [ ] are optional in both the cases. These parameters allow us to
customize the function/method.
cmp, argument allow us to override the default way of comparing elements of list. By
default, sort determines the order of elements by comparing the elements in the list
against each other. To overside this, we can use a user defined function which should
take two values and return -1 for , 0 for
Example
The parameter is for specifying a function that transforms each element of list
before comparison. We can use predefined functions or a user defined function here. If
its user defined then, the function should take a single argument and return a key
which can be used for sorting purpose.
Reverse parameter can have a boolean value which is used to specify the order of
arranging the elements of list. Value for reverse will arrange the elements of list
in descending order and value for reverse will arrange the elements in ascending
order. Default value of this parameter is False.
208
sorted ( ) function also behaves in similar manner except for it produce a new sorted
list, so original is not changed. This function can also be used to sort any iterable
collection. As sort ( ) method does not create a new list so it can be little faster.
Example
>>> L1.sort ( )
>>> print L1
will produce
>>> L2.sort ( )
>>> print L2
will produce
will produce
Here we have specified len ( ) built in function, as key for sorting. So the list will get
sorted by the length of the strings, i.e., from shorted to longest.
sort will call len ( ) function for each element of list and then these lengths will be used
for arranging elements.
>>> L4.sort ( )
>>> print L4
will produce
209
[10, 20, 30,
>>>L4.sort (reverse = True)
30, 20, 10]
>>> def compare (str):
... return len (str)
>>> L2.sort (key=compare)
>>> L2
List as arguments
When a list is passed to the function, the function gets a reference to the list. So if the
function makes any changes in the list, they will be reflected back in the list.
Example
L [i] += 10
>>> X = [1, 2, 3, 4, 5]
>>> print X
look like
210
Note: Here, it becomes important to distinguish between the operations which
modifies a list and operation which creates a new list. Operations which create a new
list will not affect the original (argument) list.
created.
>>> a = [2, 4, 6]
>>> b = a
will map b to a. To check whether two variables refer to same object (i.e. having same
>>> a is b
>>> a = [2, 4, 6]
>>> b = [2, 4, 6]
>>> a is b
False
In first example, Python created one list, reference by a & b. So there are two references
to the same object b. We can say that object [2, 4, 6] is aliased as it has more than one
>>> a [1] = 10
>>> print b
will print
[2, 10, 6]
211
Matrix implementation using list
We can implement matrix operation using list. Matrix operation can be implemented
using nested list. List inside another list is called nested list.
Example
Write a program to input any matrix with mXn, and print the number on the output
screen in matrix format.
Matrix creation
Program 1
212
Output
>>>
output is
10 20 30
40 50 60
70 80 90
>>>
Program 2
import random
for i in range(m):
213
for j in range(n):
a[i][j]=input()
for i in range(m):
for j in range(n):
print a[i][j],'\t',
Output
>>>
output is
1 2 3
4 5 6
7 8 9
>>>
214
Matrix Addition
Write a program to input any two matrices and print sum of matrices.
import random
for i in range(m1):
for j in range(n1):
a[i][j]=input()
for i in range(2):
for j in range(2):
b[i][j]=input()
for i in range(m1):
for j in range(n1):
c[i][j]=a[i][j]+b[i][j]
print c[i][j],'\t',
else
215
Output
>>>
output is
3 3
3 3
Example
Write a program to input any two matrices and print product of matrices.
import random
for i in range(m1):
for j in range(n1):
a[i][j]=input()
216
m2=input ("Enter total number of rows in the second matrix")
for i in range(m2):
for j in range(n2):
b[i][j]=input()
if (n1==m2):
for i in range(m1):
for j in range(n2):
c[i][j]=0
for k in range(n1):
c[i][j]+=a[i][k]*b[k][j]
print c[i][j],'\t',
else:
Output
>>>
217
Enter total number of columns in the second matrix2
4 4
4 4
>>>
Example
Write a program to input any matrix and print both diagonal values of the matrix.
import random
if (m==n):
for i in range(m):
for j in range(n):
a[i][j]=input()
for i in range(m):
print a[i][i],'\t',
k=m-1
for j in range(m):
print a[j][k],'\t',
218
k-=1
else:
Output
>>>
First diagonal
1 5 9
Second diagonal
3 5 7
>>>
Example
Write a program to pass any list and to arrange all numbers in descending order.
219
def arrange (l,n):
for i in range(n-1):
for j in range(n-i-1):
if l[j]>l[j+1]:
temp=l[j]
l[j]=l[j+1]
l[j+1]=temp
Output
>>>
>>> l=[7,5,8,2,9,10,3]
>>> print l
[10, 9, 8, 7, 5, 3, 2]
>>>
Example
Write a program to input nXm matrix and find sum of all numbers using function.
Function:
def summat(a,m,n):
s=0
for i in range(m):
for j in range(n):
s+=a[i][j]
return s
220
Function call
import random
import mataddition
for i in range(m):
for j in range(n):
a[i][j]=input()
s=mataddition.summat(a,m,n)
print s
Output
>>>
10
>>>
Example
count = -1
for list in a:
221
count + = 1
print item,
123
45
678
222
EXERCISE
1. Define list
(i)
(ii)
(iii)
b) a= [1, 2, 3, None, ( ), [ ]}
print len(a)
(iii) 5 (iv) 6
(v) 7
A=[2,4,6,8,10]
L=len(L)
S=0
for I in range(1,L,2):
S+=A[I]
l=range(n)
print l
for i in (n);
l[i]=input("enter element")
223
print "All elements in the list on the output screen"
for i on range(n):
print l[i]
5. Write a function group of list (list, size) that takes a list and splits into smaller list
of given size.
7. For each of the expression below, specify its type and value. If it generates error,
write error.
(i) x[0]
(ii) x[2]
(iii) x[-1]
(iv) x[0:1]
(v) 2 in x
(vi) x[0]=8
8. For each of the expression below, specify its type and value. If it generates error,
write error:
List A= [1, 4, 3, 0]
(ii) List A
224
(vii) List B.pop ( )
LAB EXERCISE
2. Write a function that takes a list of numbers and returns the cumulative sum; that
is, a new list where the its element is the sum of the first i+1 elements from the
original list. For example, the cumulative sum of [1, 2, 3] is [1, 3, 6].
3. Write a function called chop that takes a list and modifies it, removing the first and
last elements, and returns None. Then write a function called middle that takes a list
and returns a new list that contains all but the first and last elements.
4. Write a function called is_sorted that takes a list as a parameter and returns True if
the list is sorted in ascending order and False otherwise. You can assume (as a
precondition) that the elements of the list can be compared with the relational
operators <, >, etc.
For example, is_sorted ([1, 2, 2]) should return True and should
return False.
5. Write a function called remove_duplicates that takes a list and returns a new list
with only the unique el
same order.
6. Write a function that takes in two sorted lists and merges them. The lists may not
-in
methods or functions.
225
7. Create a list that contains the names of 5 students of your class. (Do not ask for
input to do so)
(ii) Ask the user to input one name and append it to the list
(iv) Ask user to input a number. Print the name that has the number as index
(Generate error message if the number provided is more than last index
value).
(v)
(vii) Ask the user to type a name. Check whether that name is in the list. If exist,
delete the name, otherwise append it at the end of the list.
8. Use the list of student names from the previous exercise. Create a for loop that asks
the user for every name whether they would like to keep the name or delete it.
Delete the names which the user no longer wants. Hint: you cannot go through a
list using a for loop and delete elements from the same list simultaneously because
in that way the for loop will not reach all elements. You can either use a second
copy of the list for the loop condition or you can use a second empty list to which
you append the elements that the user does not want to delete.
9. Write a function to find product of the element of a list. What happens when the
function is called with list of strings?
10. Write a program to input NXM matrix and find sum of all even numbers in the
matrix.
13. Write a program to find sum of rows and columns of the matrix.
226