



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!




Today ...
HW
Iteration (looping) allows us to repeat blocks of code
For example, instead of writing:
the list = ["spam", "ham", "eggs"]
print(the list[0])
print(the list[1])
print(the list[2])
We can use a for statement:
for v in the list: print(v)
acc = initial value # "accumulate" results in this variable for x in the list: acc = acc operation x
do something with acc
Generalizes many computations over lists
Example
the_list = [3, 4, 5, 6] diff = 50 for x in the_list: diff = diff - x print(diff)
Q: What is the value of diff after every iteration?
Works the same as other parameters
def print_list(the_list): for x in the_list: print(x)
my_list = [1, 2, 3] print_list(my_list) 1 2 3 print_list(["spam", "ham", "eggs"]) spam ham eggs
range allows us to iterate a fixed number of times
for i in range(3): print("spam")
Q: What is printed?
range also gives access to list indexes
the list = [10, 20, 30] the length = len(the list) for i in range(the length): the list[i] = the list[i] * 2
Q: What does this do to the list?