You are on page 1of 31

Lecture 4:

Collection Data Types I

Hrishav Tandukar
hrishav.tandukar@islingtoncollege.edu.np

CS4051 Fundamentals of Computing


Last week
• branching - if/elif/else
• iteration - for loops
• iteration - while loops

CS4051 Fundamentals of Computing 2


Today
• Have seen primitive data types: int,float,bool,string
• Introduce compound data types
• Lists
• Tuples

CS4051 Fundamentals of Computing 3


Iteration/Control Flow – for loops
• iterate (loop) through numbers in a sequence
>>>
0
for i in range(5):
1
print(i)
2
# for <variable> in range(n): 3
# <expression> 4
# ...
# range generates numbers from 0 to n-1

CS4051 Fundamentals of Computing 4


range(start,stop,step)
• default values are start = 0 and step = 1, both are
optional, but can be overwritten
• loop until value is stop – 1
mysum = 0 >>>
for i in range(5,10): 35
mysum = mysum + i
print(mysum)
5+6+7+8+9 = 35

CS4051 Fundamentals of Computing 5


range(start,stop,step) >>>
for i in range(5,10,2): 5
print(i) 7
9
for i in range(5,11,2):
print(i) >>>
5
for i in range(5,12,2):
7
print(i)
9
11
CS4051 Fundamentals of Computing 6
range(start,stop,step) >>>
5
for i in range(5,0,-1): 4
print(i) 3
2 >>>
1 5
for i in range(5,-1,-1): 4
print(i)
3
2
1
0
CS4051 Fundamentals of Computing 7
Lists
• ordered sequence of information, accessible by index
• a list is denoted by square brackets, []
• a list contains elements
• usually of the same type (e.g., all integers)
• can contain mixed types
• list elements can be changed so a list is mutable
a = [1, 2, 3, 4, 5, 6] # a list
b = [1, ”Hello”, 2.0, True] # another list

CS4051 Fundamentals of Computing 8


List indices and ordering
• list indices start at 0
a = [34,22,54,99,45] # a list of numbers

0 1 2 3 4

print(a[0]) # prints out 34


print(a[4]) # prints out 45
print(a[5]) # gives an error

CS4051 Fundamentals of Computing 9


List indices and ordering
• lists support negative indexing too, starting at -1 from the end
a = [34,22,54,99,45] # a list of numbers

-5 -4 -3 -2 -1

print(a[-1]) # prints out 45


print(a[-5]) # prints out 34
print(a[-6]) # gives an error

CS4051 Fundamentals of Computing 10


len() function
• len() returns the length(the number of items) of a list
a = [“h”, “e”, “l”, “l”, “o”]
print(len(a)) # prints out 5

b = [] # an empty list
print(len(b)) # prints out 0

CS4051 Fundamentals of Computing 11


len() function
• len() returns the length(the number of items) of a list
a = [“h”, “e”, “l”, “l”, “o”]
print(len(a)) # prints out 5

b = [] # an empty list
print(len(b)) # prints out 0

notice that here a function is taking another function as


a parameter, the print function is taking the len function
as a parameter which is taking a parameter itself and
returning some value

CS4051 Fundamentals of Computing 12


Changing elements
• lists are mutable, their structure and content can be changed
• assigning to an element at an index changes the value
L = [2, 1, 3]
L[1] = 5 # puts 5 at index 1
• L is now [2, 5, 3]

CS4051 Fundamentals of Computing 13


Operations on lists - Add
• add elements to the end of the list with L.append(element)
• mutates the list!
L = [2,1,3]
L.append(5) # L is now [2,1,3,5]

CS4051 Fundamentals of Computing 14


Operations on lists - Add
• add elements to the end of the list with L.append(element)
• mutates the list!
L = [2,1,3]
L.append(5) # L is now [2,1,3,5]
What is this dot?
• lists are python objects, everything in Python is an object
• objects have data, methods/functions (remember OOP)
• access these functions by object_name.function_name()
• we will learn more about these later

CS4051 Fundamentals of Computing 15


Operations on lists - Add
• to combine lists together use concatenation, + operator, gives a new list
• mutate lists with L.extend(some_list), adds a list of numbers to the end
L1 = [2, 1]
L2 = [4, 5]
L3 = L1 + L2 # L3 is [2, 1, 4, 5], L1 & L2 unchanged
L1.extend([0, 6]) # L1 is now [2, 1, 0, 6]

CS4051 Fundamentals of Computing 16


Operations on lists - Remove
• delete element at a specific index with del(L[index])
• remove element at end of list with L.pop(), returns the removed element
• remove a specific element with L.remove(element)
• looks for the element and removes it
• if element occurs multiple times, removes first occurrence
• if element not in list, gives an error

CS4051 Fundamentals of Computing 17


Operations on lists - Remove
L = [2, 1, 3, 6, 3, 7, 0] # a list of numbers
L.remove(2) # mutates L = [1, 3, 6, 3, 7, 0]
L.remove(3) # mutates L = [1, 6, 3, 7, 0]
del(L[1]) # mutates L = [1, 3, 7, 0]
L.pop() # returns 0 and mutates L = [1, 3, 7]

CS4051 Fundamentals of Computing 18


Iterating over a list
• remember, list indices start at 0
• so any list would have indices from 0 to len(L)-1
L = [2, 43, 21, 5, 46]
print(len(L)) # 5

indices 0 1 2 3 4
elements 2 43 21 5 46
• the indices of the list need to be generated sequentially in order to access the elements
iteratively

CS4051 Fundamentals of Computing 19


Iterating over a list- using for loop
L = [2, 43, 21, 5, 46]
print(len(L)) # 5
indices 0 1 2 3 4
elements 2 43 21 5 46

for i in range(len(L)):
print(L[i]) # print the element at index i
• range(len(L)) -> range(5) -> 0 to 4 which are the indices of the list

20
CS4051 Fundamentals of Computing
Iterating over a list – for each loop
• a more simpler way using for each loop
for <element> in <list>:
<expression>
... >>>
2
L = [2, 43, 21, 5, 46]
43
for each in L:
21
print(each)
5
46
CS4051 Fundamentals of Computing 21
Iterating over a list – for each loop
• a more simpler way using for each loop note that each is just a variable
for <element> in <list>: here, any other variable name can
be used
<expression>
... >>>
2
L = [2, 43, 21, 5, 46]
43
for each in L:
21
print(each)
5
46
CS4051 Fundamentals of Computing 22
Iterating through a list – for each loop
fruits = [“apple”, “orange”, “mango”]

for fruit in fruits:


print(fruit)

>>>
apple
orange
mango

CS4051 Fundamentals of Computing 23


Membership operators
• can check if an element is a member of a list with in

fruits = [“apple”, “orange”, “mango”]

if “apple” in fruits: if “potato” in fruits:


print(“fruit”) print(“fruit”)
else: else:
print(“not fruit”) print(“not fruit”)

CS4051 Fundamentals of Computing 24


Iterating through a list
• compute the sum of elements of a list

L = [22, 33, 44, 55] L = [22, 33, 44, 55]


total = 0 total = 0
for i in range(len(L)): for number in L:
total += L[i] total += number
print(total) print(total)

• both would give out the same result here

CS4051 Fundamentals of Computing 25


Tuples
• an ordered sequence of elements
• can mix element types
• tuples once created cannot be changed, tuples are immutable
• represented with parentheses ()
t = () # empty tuple
t = (“python”, 3, 5) # a tuple with 3 elements
print(len(t)) # 3

CS4051 Fundamentals of Computing 26


Indices in tuples
• Indexing is same as in lists, but tuples are immutable
t = (1, 23, 43, 4)
print(t[0]) # 1
print(t[-1]) # 4
t[1] = 4 # gives error, can’t modify tuples!
t.append(12) # error, can’t modify tuples!

CS4051 Fundamentals of Computing 27


Iterating through tuples
• works the same way as for lists
T = (22, 33, 44, 55)
T = (22, 33, 44, 55)
for number in T:
for i in range(len(T)):
print(number)
print(T[i])

• since tuples are immutable and cannot be modified, they are useful for storing
constants

CS4051 Fundamentals of Computing 28


Tuple uses example
• conveniently used to swap variable values

x = y temp = x (x, y) = (y, x)


y = x x = y
y = temp

CS4051 Fundamentals of Computing 29


End of Lecture 4

CS4051 Fundamentals of Computing 30


Thank you !
Any questions ?

CS4051 Fundamentals of Computing 31

You might also like