Why do we use `range` here?


Why do we have to use the range function here?

FAQ: Learn Python - Lists and Functions - Modifying each element in a list in a function

We use range because it returns an iterator that matches the indexes of our list.

for i in range(len(our_list)):

The iteration will be from 0 to len(our_list) - 1

print range(len([1, 2, 3, 4, 5, 6]))

# [0, 1, 2, 3, 4, 5]

Note that the indexes are in the range.


Thanks! Maybe I should have been a little more clear though - why do we use range as opposed to ‘for i in x:’ (for example)? I tried both and found that with the latter I got an error.


We must access the element by index, if changing it. Accessing by item does not permit changing the element since we need an index to do that.

for item in our_list:
    item = 'new assignment'

The above will not work.

for x in range(len(our_list)):
    our_list[x] = 'new assignment #' + x

I’m just guessing at what the exercise expects. Please post the URL to the exercise.


Thanks so much. That makes sense. And one last question - ‘for item in our_list: our_list[item] = new assignment’ wouldn’t work? (i.e., you need range and/or len() to access index?).


To make this work, we need to know the index of item.

for item in our_list:
    our_list[our_list.index(item)] = 'new item'

The only problem is that item could be in multiple places (more than one index), in which case only the first occurence will ever be pointed to since the method works from left to right. On the other hand in range()is sequential and consecutive so we can be certain to reach every index, in order from start to finish.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.