# Help on using lists inside a function

#1

While outside of a function, in isolation I can use:

for items in to run through every item in the list, in the example below i need to replace list name with range(0, len(list_name)) else it throws the following error:

Traceback (most recent call last):
File "python", line 9, in
File "python", line 5, in double_list
IndexError: list index out of range

Any help on this?

``````n = [3, 5, 7]

def double_list(x):
for i in x:
x[i] = x[i] * 2
return x
# Don't forget to return your new list!

print double_list(n)``````

#2

well, it is important to realize what i is in the for loop:

``````n = [3, 5, 7]

def double_list(x):
for i in x:
print i
return x
# Don't forget to return your new list!

print double_list(n)``````

so i are the numbers in the list, not the indexes. If you use range, you will the indexes, rather then the numbers in the lists. Hope this helps

#3

But in either case, won't we be acting on each list element. What i mean to ask is, even when we iterate through the index number we get each list item which we get otherwise also as we iterate through each item in x and in this case multiply by 2 to perform the task in the function. But I'm getting an error in the second method above.

#4

`i` holds the number in the list (3,5 and 7 in turn), which you then use to access the index (which is wrong):

``````n = [3, 5, 7]

def double_list(x):
for i in x:
print i
print x[i]
return x
# Don't forget to return your new list!

print double_list(n)``````

while if you use range, i holds the index. There is a fundamental difference difference:

``for i in range(0,len(x))``

`i` will hold the index (0,1,2) which you can use to access and change the value at a index. If you use your second method:

``for i in x:``

`i` will not hold the index, but rather the actual numbers (3,5,7). Which means you can't access the index. (since the numbers in the list don't correspond with the indexes.

when you use the second method, you try access the indexes, with the values in the list:

``````i[3]
i[5]
i[7]``````

which are all outside of the index. the square brackets are used to access items in a list based on index

#5

def double_list(x):
for i in x:
i = i * 2
return x

Thanks a lot. It's clear now. Based on what you explained, I deduced that the above piece of code does nothing of significance to the original list. No item level modification et al and hence doesn't work and so we make use of range() function to make element level list modification.

#6

no, this will not update anything inside the list. It only updates i inside the for loop, and that is it (which is fine if you just want to print the result, but not if you want to modify the list). So, you have to use range to access the indexes, so you can actually update the list

#7

Thanks once again for so much help. Really clarifies a lot of concepts.