Modifying each element in a list in a function


Modifying each element in a list in a function

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

Why does this not work correctly? Why does the x need to be range(0, len(x))? This method works fine for printing every element in the list but when changing every element like this it doesn't work?

n = [3, 5, 7]

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


What values get assigned to i? Does it make sense to use those as indexes?
What does range return? What values would you obtain from iterating through that result?


the index values are assigned to i. i know this because of i replace (x[i] = x[i] * 2) with print i i get 0 1 2. i goes from 0 to 2 accessing every element of the array. so for instance x[0] = x[0] * 2 should take the first element of the array multiply it by 2 and assign that to the first element and then keep doing that for each element of the array.


Those are not the values that i will take on in the code you posted

Note that 0 1 2 aren't mentioned anywhere in the code, where would they be coming from?
As you said, you can use print to find out what a variable refers to


im not sure what i did before. i think i figured things out though thanks


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