Iterating Through Lists


#1

Hello,
I’m not sure where to ask this question, since I can’t seem to find any threads regarding this particular exercise on Python. I’ve been struggling to understand the second method of iterating through indexes-using range(len(list)) instead of the name of the list. I’m having a hard time understanding why this would yield similar results to the first method of just using the name of the list. Doesn’t the second method only take into consideration the number of elements rather than the content? Furthermore, how does it allow for the modification of the given list?

Thank you for your time!


FAQ: Learn Python - Lists and Functions - Iterating over a list in a function
#2

range produces a list, so for example:

the_list = ['a', 'b', 'c']
print range(len(the_list)) # will output: [0, 1, 2]

so now have the indexes/indices for the_list. Which we can use to get the values:

the_list = ['a', 'b', 'c']
for i in range(len(the_list)):
   print the_list[i]

but then i prefer to use what you refer to as first method:

the_list = ['a', 'b', 'c']
    for v in the_list:
        print v

indices/indexes are useful when we want to update elements in the list:

the_list[i] = 'new value'