Help with 7.12 Iterating through a list


#1

Link:
https://www.codecademy.com/courses/learn-python/lessons/lists-and-functions/exercises/printing-out-a-list-item-by-item-in-a-function?action=resume_content_item

The solution for this exercise is:

n = [3, 5, 7]

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

print_list(n)

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

n = [3, 5, 7]

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

print_list(n)

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?


#2

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.


#3

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


#4

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]
>>>