Professional Documents
Culture Documents
Week 4 Lecture Slides
Week 4 Lecture Slides
Hrishav Tandukar
hrishav.tandukar@islingtoncollege.edu.np
0 1 2 3 4
-5 -4 -3 -2 -1
b = [] # an empty list
print(len(b)) # prints out 0
b = [] # an empty list
print(len(b)) # prints out 0
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
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”]
>>>
apple
orange
mango
• since tuples are immutable and cannot be modified, they are useful for storing
constants