1. CS303E Slideset 2: 1
CS303E Slideset 2: 1 Simple Python
Python
Foundation of Computer Programming
CYBR 3511
Lecture 6
Lists and Tuples
2. CS303E Slideset 2: 2
CS303E Slideset 2: 2 Simple Python
Python
2
Topics
Lists
Functions and Methods for Lists
Tuples
Functions and Methods for Tuples
3. CS303E Slideset 2: 3
CS303E Slideset 2: 3 Simple Python
Python
3
Lists
A list an ordered sequence of items of any type.
lists are mutable. If we change a list, it doesn’t create
a new copy; it changes the actual contents of the list.
4. CS303E Slideset 2: 4
CS303E Slideset 2: 4 Simple Python
Python
4
Creating Lists
Creating a simple list L: L= [1,2,3]
Lists can be created with the l i s t class constructor
>>> l i s t ( )
[ ]
>>> l i s t ( [ 1 , 2, 3] )
# c r eat e em
pt y l i s t , w
i t h c ons t r uc t or
# c r eat e l i s t [ 1, 2, 3]
[ 1, 2, 3]
>>> l i s t ( [ " red " , 3, 2 . 5 ] ) # c r e a t e heterogeneous l i s t
# c r e a t e l i s t , no e x p l i c i t c o n s t r u c tor
# not an a c t u al l i s t
# c r e a t e l i s t using range
# c r e a t e c h a r a c te r l i s t from s t r i n g
[ ’ r ed’ , 3, 2. 5]
>>> [ " r ed" , 3, 2. 5]
[ ’ r ed’ , 3, 2. 5]
>>> r ange ( 4)
r ange ( 0, 4)
>>> l i s t ( r ange ( 4) )
[ 0, 1, 2, 3]
>>> l i s t ( " abc d" )
[ ’ a ’ , ’ b ’ , ’ c ’ , ’d ’ ]
5. CS303E Slideset 2: 5
CS303E Slideset 2: 5 Simple Python
Python
5
Slicing Lists
Similar to strings as well, lists can be sliced
To slice elements within a range start_index and end_index
(inclusive), we can use [start_index : end_index+1]
>>> grades = ["A", "B", "C", "D", "F"]
>>> grades[1:3]
['B', 'C']
To slice elements from the beginning to a certain ending
index (inclusive), we can use [: end_index+1]
>>> grades[:3]
['A', 'B', 'C']
A B C D F
0 1 2 3 4
6. CS303E Slideset 2: 6
CS303E Slideset 2: 6 Simple Python
Python
6
Sequence Operations
Lists are sequences and inherit various functions
from sequences.
Function
x in s
Description
x is in sequence s
x not in s
s1 + s2
s * n
s [ i ]
s [ i : j ]
len(s)
min(s)
max(s)
sum(s)
for loop
<, <=, >, >=
==, !=
x is not in sequences
concatenates two sequences
repeat sequence s n times
ith element of sequence (0-based)
slice of sequence sfrom i to j-1
number of elements in s
minimum element of s
maximum element of s
sum of elements in s
traverse elements of sequence
comparestwo sequences
compares two sequences
7. CS303E Slideset 2: 7
CS303E Slideset 2: 7 Simple Python
Python
7
Calling Functions on Lists
>>> l 1 = [ 1, 2, 3, 4, 5]
>>> l en( l 1 )
5
>>> m
i n( l 1 )
1
>>> m
ax( l 1 )
5
>>> s um
( l 1 )
# assumes elements are comparable
# assumes elements are comparable
# assumes summing makes sense
15
>>> l 2 = [ 1, 2, " r ed" ]
>>> s um
( l 2 )
Tr ac ebac k ( m
os t r ec ent c al l l as t ) :
Fi l e " <s t di n >" , l i ne 1, i n <m
odul e >
TypeE r r o r : unsupported operand type ( s ) f or + : ’ i n t ’ and ’ s t r
’
>>> m
i n( l 2 )
Tr ac ebac k ( m
os t r ec ent c al l l as t ) :
Fi l e " <s t di n >" , l i ne 1, i n <m
odul e >
TypeE r r o r : ’ < ’ not supported between i n s t a n c e s of ’ s t r ’ and
’ i nt ’
>>>
8. CS303E Slideset 2: 8
CS303E Slideset 2: 8 Simple Python
Python
8
Methods for Lists
These are methods from class list.
Since lists are mutable, these actually change t.
Function
t.append(x)
Description
add x to the end of t
t.count(x)
t.extend(l1)
t.index(x)
t . i n s e r t ( i , x)
t.pop()
t.pop(i)
t.remove(x)
t.reverse()
t . s o r t ( )
number of times x appearsin t
append elements of l1 to t
index of first occurence of x in t
insert x into t at position i
remove and return the last element of t
remove and return the ith element of t
remove the first occurenceof x from t
reverse the elements of t
order the elements of t
9. CS303E Slideset 2: 9
CS303E Slideset 2: 9 Simple Python
Python
9
Example
>>> l1 = [1 , 2 , 3]
>>> l1 . append (4) # add 4 to the end of l1
>>> l1 # note : changes l1
[1 , 2 , 3 , 4]
>>> l1 . count (4) # count occurrences of 4 in l1
1
>>> l2 = [5 , 6 , 7]
>>> l1 . extend ( l2 ) # add elements of l2 to l1
>>> l1
[1 , 2 , 3 , 4 , 5 , 6 , 7]
>>> l1 . index (5) # where does 5 occur in l1 ?
4
>>> l1 . insert (0 , 0) # add 0 at the start of l1
>>> l1 # note new value of l1
[0 , 1 , 2 , 3 , 4 , 5 , 6 , 7]
>>> l1 . insert (3 , ’a’) # lists are heterogenous
>>> l1
[0 , 1 , 2 , ’a’, 3 , 4 , 5 , 6 , 7]
>>> l1 . remove (’a’) # what goes in can come out
>>> l1
[0 , 1 , 2 , 3 , 4 , 5 , 6 , 7]
10. CS303E Slideset 2: 10
CS303E Slideset 2: 10 Simple Python
Python
10
Traversing List with a For Loop
Method2:
for i in range(len(mylist)):
body
f or u i n [ 2, 3, 5, 7] :
pr i nt ( u, end=" " )
Method1
for u in l i s t :
body
myList = [1, 2, 3]
for i in range(len(myList)):
print(myList[i], end = " ")
print()
11. CS303E Slideset 2: 11
CS303E Slideset 2: 11 Simple Python
Python
11
Get a list as input from user
# creating an empty list
lst = []
# number of elements as input
n = int(input("Enter number of elements : "))
# iterating till the range
for i in range(0, n):
n = int(input("Enter the element “,i,”:”))
lst.append(element )
# adding the element
12. CS303E Slideset 2: 12
CS303E Slideset 2: 12 Simple Python
Python
12
Multi-Dimensional Lists
Lists can be nested so as to create a multi-dimensional
list
>>> myList = [[1, 2, 3], [4, 5, 6]]
>>> myList[0]
[1, 2, 3]
>>> myList[0][0]
1
>>> myList[0][1]
2
>>> myList[1][0]
4
>>>
13. CS303E Slideset 2: 13
CS303E Slideset 2: 13 Simple Python
Python
13
Traversing Multi-Dimensional Lists
How can we iterate over the elements of a n-dimensional
list?
By using n loops
my2DList = [[1, 2, 3], [4, 5, 6]]
for i in range(len(my2DList)):
for j in range(len(my2DList[i])):
print(my2DList[i][j], end = " ")
print()
1 2 3
4 5 6
Output:
14. CS303E Slideset 2: 14
CS303E Slideset 2: 14 Simple Python
Python
14
Tuples
A tuple is essentially an immutable list. Below is a list with three
elements and a tuple with three elements:
Tuples are enclosed in parentheses
Indexing and slicing work the same as with lists.
As with lists, you can get the length of the tuple by using the len
function, and, like lists, tuples have count and index methods.
However, since a tuple is immutable, it does not have any of the
other methods that lists have, like sort or reverse, as those
change the list.
L = [1,2,3]
t = (1,2,3)
t1 = (1, 2, 3)
t2 = (“a”, “b”, “c”, ”d”)
print(t1)
print(t2)
15. CS303E Slideset 2: 15
CS303E Slideset 2: 15 Simple Python
Python
15
Tuples
Like lists, tuples can:
Contain any and different types of elements
Contain duplicate elements (e.g., (1, 1, 2))
Be indexed exactly in the same way (i.e., using the [ ]
brackets)
Be sliced exactly in the same way (i.e., using the [::]
notation)
Be concatenated (e.g., t = (1, 2, 3) + (“a”, “b”, “c”))
Be repeated (e.g., t = (“a”, “b”) * 10)
Be nested (e.g., t = ((1, 2), (3, 4), ((“a”, “b”, ”c”), 3.4))
Be iterated over
16. CS303E Slideset 2: 16
CS303E Slideset 2: 16 Simple Python
Python
16
Functions and Methods for Tuples
Python provides two built-in methods that you can
use on tuples.
count(x)
Index(x)
t1 = (1, 2, 3, 1, 5, 1)
print(t1.count(1))
print(t1.index(1))
The count(x) function returns the number of
elements with the specified value x (e.g., x is 1
in this example)
The index(x) function returns the index of
the first element with the specified value x
(e.g., x is 1 in this example)
Output:
3
0
In fact, Python has only these two built-in functions that can be
used on tuples
18. CS303E Slideset 2: 18
CS303E Slideset 2: 18 Simple Python
Python
18
Example: Matrix-Matrix Addition
import random
def buildSquareMatrix(m, n):
if m == n:
matrix = []
for i in range(m):
row = []
for j in range(n):
row.append(random.randint(1, 100))
matrix.append(row)
return matrix
else:
return "This function builds only square matrices with random
integersn"
19. CS303E Slideset 2: 19
CS303E Slideset 2: 19 Simple Python
Python
19
Example: Matrix-Matrix Addition
#This function assumes equal square matrices (i.e., each matrix is a square matrix
#and both have the same numbers of rows and columns)
def addMatrices(a, b):
m = n = len(a)
c = []
for i in range(m):
row = []
for j in range(n):
row.append(a[i][j] + b[i][j])
c.append(row)
return c
20. CS303E Slideset 2: 20
CS303E Slideset 2: 20 Simple Python
Python
20
Example: Matrix-Matrix Addition
def printMatrix(a):
for i in a:
for j in i:
print(j, end = "t")
print()
print()
a = buildSquareMatrix(5, 5)
b = buildSquareMatrix(5, 5)
printMatrix(a)
printMatrix(b)
c = addMatrices(a, b)
printMatrix(c)
21. CS303E Slideset 2: 21
CS303E Slideset 2: 21 Simple Python
Python
21
Exercises
Q1:Write a function to sum all the items in a list list1.
Input
list1 = [5, 10, 15]
Output
Result : 30
Q2:Write a function to get the largest number from a list list1
Input
list1 = [5, 10, 15]
Output
Result : 15
Q3: Write a function to count the number of elements x in a list list1
Input
list1 = [5, 5, 20,5]
x=5
Output
Result : 3
Q4:Write a function to multiply all the items in a list list1
Input
list1 = [5, 2, 20]
Output
Result : 200
22. CS303E Slideset 2: 22
CS303E Slideset 2: 22 Simple Python
Python
22
Exercises
Q5: Write a function to find value x in a given list list1 , and if it is
present, replace it with 200. Only update the first occurrence of an item.
Input
list1 = [5, 10, 15, 20, 25, 50, 20]
x=20
Output
Result : [5, 10, 15, 200, 25, 50, 20]
Q6: Write a function to square each element of a list.
Input
list1 = [2, 3, 4, 5, 6]
Output
Result : 4 9 16 25 36
Q7: Write a function to filter odd and even number from a list.
Input
Given [2, 23, 24, 51, 46, 67]
Output
Even [2, 24, 46] Odd [23, 51, 67]
23. CS303E Slideset 2: 23
CS303E Slideset 2: 23 Simple Python
Python
23
Exercises
Q8: Write a function to remove all occurrences of item x in a given list
list1 .
Input
list1 = [5, 10, 15, 20, 25, 50, 20]
X=20
Output
Result : [5, 10, 15, 25, 50]
Q9: Write a function to remove duplicate items from a given list list1.
Input
list1= [2,3,4,5,2,6,3,2]
Output
Result: [2, 3, 4, 5, 6]
24. CS303E Slideset 2: 24
CS303E Slideset 2: 24 Simple Python
Python
24
HomeWork2
Q1: Write a function to get the frequency of all elements in a list.
Input
list1 = [3, 5, 4, 3, 3, 4, 5, 2]
Output
The list frequency of elements is :
Element Frequency
3 3
5 2
4 2
2 1
Q2: Write a 3 functions to find
• The union between two lists A and B
• The intersection between two lists A and B
• The difference between two lists A and B
Input
A = [1, 5, 4,2]
B= [1, 10, 2]
Output
Union(A,B): [1, 5, 4,2,10]
Intersection(A,B): [1,2]
Difference (A,B): [5,4]