Help with 7.12 Iterating through a list



The solution for this exercise is:

n = [3, 5, 7]

def print_list(x):
for i in range(0, len(x)):
print x[i]


My question is, why don’t we use this:

n = [3, 5, 7]

def print_list(x):
for i in x:
print i


The second piece of code seems simpler. What’s the point of using range(1, len()) when I am just going to iterate through the whole list?


It depends on the scenario. Sometimes we need the index so use range() to generate a list of indexes. This gives us access to modify the element. If all we want is Read-Only access, then i in x is how we can do that. We cannot modify any elements in read-only loops.


Thank you. So to modify the list, we need to access the items via the indices?


Correct. Be careful when modifying a list that the length does not change inside the loop. Elements can be modified without issue.

>>> def double_value_at_index(lst, index):
    if index in range(len(lst)):
        lst[index] *= 2
    return lst

>>> my_list = [2,5,9,14,20]
>>> print (double_value_at_index(my_list, 3))
[2, 5, 9, 28, 20]