0% found this document useful (0 votes)
23 views34 pages

Chapter 2 List

Uploaded by

ankush sarma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views34 pages

Chapter 2 List

Uploaded by

ankush sarma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

Chapter 2

After studying this lesson, students will be able to:


Understand the concept of mutable sequence types in Python.
Appreciate the use of list to conveniently store a large amount of data in memory.
Create, access & manipulate list objects
Use various functions & methods to work with list
Appreciate the use of index for accessing an element from a sequence.

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.

Its syntax is:

Variable name [index] (variable name is name of the list).

ist. Index here, has to be an integer value-


which can be positive or negative. Positive value of index means counting forward from
beginning of the list and negative value means counting backward from end of the list.
Remember the result of indexing a list is the value of type accessed from the list.

Index value Element of the list

0, -size 1st

1, -size +1 2nd

193
2, -size +2 3rd

.
.
.

size -2, -2 2nd last

size -1, -1 last

Please note that in the above example size is the total number of elements in the list.

k at some example of simple list:

i) >>>L1 = [1, 2, 3, 4] # list of 4 integer elements.

ii) >>> #list of 3 string elements.

iii) >>>L3 = [ ] # empty list i.e. list with no element

iv) >>>L4 = # list with different types of elements

v) >>>L5 = [1, 2, [6, 7, 8], 3] # A list containing another list known as


nested 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

>>> print L1 # modified list

[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.

State diagram for the list looks like:

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:

i) By enclosing elements in [ ], as we have done in above examples.

ii) Using other Lists

Example

L5=L1 [:]

Here L5 is created as a copy of L1.

>>>print L5

L6 = L1 [0:2]

>>>print L6

will create L6 having first two elements of L1.

iii) List comprehension

Example

>>>n = 5

195
>>>l = range(n)

>>>print l

[0, 1, 2, 3, 4]

Example

>>> S= [x**2 for x in range (10)]

>>> print S

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

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]

>>> B = [value *3 for value in A]

Here B will be created with the help of A and its each element will be thrice of
element of A.

>>> print B

[9, 12, 15]

Comprehensions are functionally equivalent to wrting as:

>>>B = [ ]

>>>for i in A

B. append (i*3)

Similarly, other comprehensions can be expended.

Example

>>> print B

[9, 12, 15]

>>>C = [i for i in S if i % 2 = = 0]

196
>>>print C

[0, 4, 16, 36, 64]

iv) Using built-in object

L = list ( ) will create an empty list

Example

>>>l = list ( )

>>>print l

[ ] # empty list

Or

L = list (sequence)

Example

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

>>>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=[ ]

Creates one list mapped to both A & B

Example

>>>A = B = [10, 20, 30]

>>> print A, B

[10, 20, 30] [10, 20, 30]

ii) A=[]

B=A

Will also create one list mapped to both

197
Example
>>> A = [1, 2, 3]

>>> B = A

>>> print A, B

[1, 2, 3] [1, 2, 3]

Accessing an element of list


For accessing an element, we use index and we have already seen example doing so. To
access an element of list containing another list, we use pair of index. Lets access
elements of L5 list. Also a sub-list of list can be accessed using list slice.

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

>>>print L5 [2] [0]

>>>print L5 [2] [2]

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.

Its Syntax is:

seq = L [start: stop: step]

Where start, stop & step- all three are optional. If you omit first index, slice starts from

Example

>>>L2 [0:2]

Example

>>>list = [10, 20, 30, 40, 50, 60]

>>> list [::2] # produce a list with every alternate element

[10, 30, 50]

>>>list [4:] # will produce a list containing all the elements from 5th position
till end

[50, 60]

Example

>>>list [:3]

[10, 20, 30]

>>>list [:]

[10, 20, 30, 40, 50, 60]

Example

>>> list [-1] -

60

will produce a list with every other element

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

will produce following output

1254

(ii) for i in L1:

print i,

will also produce the same output

(iii) i=0

while i < len [L1]:

print L1 [i],

i+=1

OR

i= 0

L = len (L1)

while i < L :

print L1 [i],

i+=1

will also produce the same output.

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.

(iv) for i in range ( len (L1)):

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.

Note: for loop in empty list is never executed:

Example

for i in [ ]:

print i

Accessing list with negative index

i=1

while i < len (L1):

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.

Appending in the list


Appending a list is adding more element(s) at the end of the list. To add new elements
at the end of the list, Python provides a method append ( ).

Its Syntax is:

List. append (item)

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

will produce following on screen

[1, 2, 5, 4, 70]

Example

>>>L4.append (30) # will add 30 at the end of the list

>>>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

>>>A = [100, 90, 80, 50]

>>> L1. extend (A)

>>> print L1

will

[1, 2, 5, 4, 70, 100, 90, 80, 50]

>>>print A

[100, 90, 80, 50]

Example

>>>B.extend (c)

>>>print B

202
Remember:

Updating array elements


Updating an element of list is, accomplished by accessing the element & modifying its
value in place. It is possible to modify a single element or a part of list. For first type, we
use index to access single element and for second type, list slice is used. We have seen
examples of updations of an element of list. Lets update a slice.

Example

>>> L1 [1:2] = [10, 20]

>>> print L1

will produce

[1, 10, 20, 4, 70, 100, 90, 80, 50]

Example

>>>A=[10, 20, 30, 40]

>>>A [1:4] = [100]

>>>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

[1, 10, 20, 4, 70, 100, 90, 80, 50,

203
Example

>>> [1, 2, 3] + [4, 5, 6]

[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

>>> str([11, 12] >>>

, 12]

34 ) or >>>

Deleting Elements
It is possible to delete/remove element(s) from the list. There are many ways of doing
so:

(i) If index is known, we can use pop ( ) or del

(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.

(iv) Using assignment operator

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.

Its syntax is:

List.pop ([index])

Example

>>> L1 = [1, 2, 5, 4, 70, 10, 90, 80, 50]

>>> a= L1.pop (1) # here the element deleted will be returned to

>>> print L1

[1, 5, 4, 70, 10, 90, 80, 50]

>>> print a

If no index value is provided in pop ( ), then last element is deleted.

>>>L1.pop ( )

50

del removes the specified element from the list, but does not return the deleted
value.

>>> del L1 [4]

>>> print L1

[1, 5, 4, 70, 90, 80]

remove ( )
In case, we know the element to be deleted not the index, of the element, then remove (
) can be used.

>>> L1. remove (90)

will remove the value 90 from the list

205
>>> print L1

[1, 5, 4, 70, 80]

del () with slicing


Consider the following example:

Examples

>>> del L1 [2:4]

>>>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] = [ ]

Will delete the slice

>>>print L5

[1, [6, 7, 8], 3]

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.

Other functions & methods


insert ( )
This method allows us to insert an element, at the given position specified by its index,
and the remaining elements are shifted to accommodate the new element. Insert (

() requires two arguments-index value and item value.

206
Its syntax is

list. insert (index, item)

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

>>> L1.insert (3,100)

>>>print L1

will produce

[1, 5, 80, 100]

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 len(L1)

>>> L1.insert (6, 29)

>>> L1.insert (-2, 46)

>>>print L1

will produce

[46, 1, 5, 80, 100, 29]

reverse ( )
This method can be used to reverse the elements of the list in place

Its syntax is:

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

[29, 100, 80, 5, 1, 46]

Following will also result into reversed list.

>>>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.

Its Syntax are:

sort ([cmp [, key [, reverse]]])

sorted (list [, cmp [, key [, reverse]]])

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

argument is preferred over as it produces list faster.

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

[1, 5, 29, 46, 80, 100]

>>> L2.sort ( )

>>> print L2

will produce

>>> L2.sort (key=len)

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

def add_Const (L):

for i in range (len (l)):

L [i] += 10

>>> X = [1, 2, 3, 4, 5]

>>> add_Const (X)

>>> print X

[11, 12, 13, 14, 15]

look like

So any changes made in L will be reflected to X as lists as mutable.

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.

Its syntax is:

a=[[random.random() for row in range(number of row)]for col in range(number


of column)]

Here random function is used. So we need to import random file.

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

m=input ("Enter total number of rows")


n=input ("Enter total number of columns")
l=range (m*n)
k=0
print "Input all matrix elements one after other"
for i in range(m):
for j in range(n):
l[k]=input("Enter new element")
k=k+1
print "output is"
k=0
for i in range(m):
for j in range(n):
print l[k],'\t',
k=k+1
print

212
Output

>>>

Enter total number of rows3

Enter total number of columns3

Input all matrix elements one after other

Enter new element10

Enter new element20

Enter new element30

Enter new element40

Enter new element50

Enter new element60

Enter new element70

Enter new element80

Enter new element90

output is

10 20 30

40 50 60

70 80 90
>>>

Program 2
import random

m=input("Enter total number of rows in the first matrix")

n=input("Enter total number of columns in the first matrix")

a=[[random.random()for row in range(m)]for col in range(n)]

print "Enter all elements one after other"

for i in range(m):

213
for j in range(n):

a[i][j]=input()

print "output is"

for i in range(m):

for j in range(n):

print a[i][j],'\t',

print

Output

>>>

Enter total number of rows in the first matrix3

Enter total number of columns in the first matrix3

Enter all elements one after other

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

m1=input ("Enter total number of rows in the first matrix")

n1=input ("Enter total number of columns in the first matrix")

a=[[random.random()for row in range(m1)]for col in range(n1)]

for i in range(m1):

for j in range(n1):

a[i][j]=input()

m2=input("Enter total number of rows in the second matrix")

n2=input("Enter total number of columns in the second matrix")

b=[[random.random()for row in range(m1)]for col in range(n1)]

for i in range(2):

for j in range(2):

b[i][j]=input()

c=[[random.random()for row in range(m1)]for col in range(n1)]

if ((m1==m2) and (n1==n2)):

print "output is"

for i in range(m1):

for j in range(n1):

c[i][j]=a[i][j]+b[i][j]

print c[i][j],'\t',

print

else

print

215
Output

>>>

Enter total number of rows in the first matrix2

Enter total number of columns in the first matrix2

Enter total number of rows in the second matrix2

Enter total number of columns in the second matrix2

output is

3 3

3 3

Example

Write a program to input any two matrices and print product of matrices.

import random

m1=input ("Enter total number of rows in the first matrix")

n1=input ("Enter total number of columns in the first matrix")

a=[[random.random()for row in range(m1)]for col in range(n1)]

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")

n2=input ("Enter total number of columns in the second matrix")

b=[[random.random()for row in range(m1)]for col in range(n1)]

for i in range(m2):

for j in range(n2):

b[i][j]=input()

c=[[random.random()for row in range(m1)]for col in range(n2)]

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',

print

else:

print "Multiplication not possible"

Output

>>>

Enter total number of rows in the first matrix2

Enter total number of columns in the first matrix2

Enter total number of rows in the second matrix2

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

m=input ("Enter total number of rows in the first matrix")

n=input ("Enter total number of columns in the first matrix")

a=[[random.random()for row in range(m)] for col in range(n)]

if (m==n):

for i in range(m):

for j in range(n):

a[i][j]=input()

print "First diagonal"

for i in range(m):

print a[i][i],'\t',

print

k=m-1

print "Second diagonal"

for j in range(m):

print a[j][k],'\t',

218
k-=1

else:

print "Diagonal values are not possible"

Output

>>>

Enter total number of rows in the first matrix3

Enter total number of columns in the first matrix3

First diagonal

1 5 9

Second diagonal

3 5 7

>>>

Functions with list


We can pass list value to function. Whatever modification we are doing with in
function will affect list.

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]

>>> arrange (l)

>>> print l

[10, 9, 8, 7, 5, 3, 2]

>>>

Function pass nested list also:

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

Note: This function is stored in mataddition.py

220
Function call
import random

import mataddition

m=input("Enter total number of rows in the first matrix")

n=input("Enter total number of columns in the first matrix")

a=[[random.random()for row in range(m)]for col in range(n)]

for i in range(m):

for j in range(n):

a[i][j]=input()

s=mataddition.summat(a,m,n)

print s

Output

>>>

Enter total number of rows in the first matrix2

Enter total number of columns in the first matrix2

10

>>>

Example

# Accessing the elements of a sublist

a = [[1, 2, 3], [4, 5], [6, 7, 8]]

count = -1

for list in a:

221
count + = 1

for item in list:

print item,

print

will produce the result

elements of the list at index 0 are

123

elements of the list at index 1 are

45

elements of the list at index 2 are

678

222
EXERCISE

1. Define list

2. What is the output of the following code:

a) print type ([1,2])

(i)

(ii)

(iii)

b) a= [1, 2, 3, None, ( ), [ ]}

print len(a)

(i) Syntax error (ii) 4

(iii) 5 (iv) 6

(v) 7

3. Write the output from the following code:

A=[2,4,6,8,10]

L=len(L)

S=0

for I in range(1,L,2):

S+=A[I]

4. Find the errors from the following program

n=input (Enter total number of elements)

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.

6. Write a function to find all duplicates in the list.

7. For each of the expression below, specify its type and value. If it generates error,
write error.

Assume that expressions are evaluated in order.

(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]

(i) List A.sort ( )

(ii) List A

(iii) List A.insert (0, 100)

(iv) List A.remove (3)

(v) List A.append (7)

(vi) List A+List B

224
(vii) List B.pop ( )

(viii) List A.extend ([4, 1, 6, 3])

LAB EXERCISE

1. We can use list to represent polynomial.


For Example
p (x) = -13.39 + 17.5 x + 3 x2 + x4
can be stored as
[-13.39, 17.5, 3, 1.0]
used to
represent the coefficient of the term.
Writ

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)

(i) Print the list

(ii) Ask the user to input one name and append it to the list

(iii) Print 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)

(vi) Print the list

(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.

(viii) Create a copy of the list in reverse order

(ix) Print the original list and the reversed list.

(x) Remove the last element 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.

11. Write a program to print upper triangle matrix.

12. Write a program to print lower triangle matrix.

13. Write a program to find sum of rows and columns of the matrix.

226

You might also like