Check your understanding of the previous reading: value style and index style, the enumerate, range and len functions, and updating list elements by index.
The enumerate function consumes a list and returns each element paired with its index. When the following code is run, what is printed on the first line?
values=[1,2,3]
for i, value in enumerate(values):
print(i, value)
If you are not sure, consider trying the code out above - you don't have to guess!
enumerate(values) pairs each element with its index, and indexes start at 0. On the first pass i is 0 and value is 1, so print(i, value) prints 0 1.
The range function consumes an integer and can be used to produce a list of numbers from 0 to that integer. When the following code is run, what is printed on the LAST line?
for value in range(10):
print(value)
If you are not sure, consider trying the code out above - you don't have to guess!
range(10) produces the numbers from 0 up to, but not including, 10. The loop prints them one per line, so the last line is 9.
The range and len functions can be combined to iterate through indices. When the following code is run, what is printed FIRST? Pay close attention to the code inside the for loop!
values=[6, 7, 8]
for index in range(len(values)):
print(values[index-1])
If you are not sure, consider trying the code out above - you don't have to guess!
On the first pass index is 0, so the loop prints values[0-1], which is values[-1]: the last element, 8.