10 . Modifying an element of a list in a function


#1

Hey guys i'm a bit stuck and would like some help!

This is my code:
n = [3, 5, 7]

def list_function(x):
for i in range(0, len(n)):
x[i] = x[i] * 2
return x

print list_function(n)

This is the error it tells me in the red box:
Oops, try again. list_function([6, 4]) resulted in an error: list index out of range

I am not too sure what I have done wrong!
Looking forward to a response
Thanks!! :slight_smile:


#2

Hi @nathanhlr,

Here, you are calling the len function on the global variable, n, when inside the function, you should instead be processing the local parameter, x ...

    for i in range(0, len(n)):

#3

I changed it to x but the code still will not work! do you know if I have done anything else wrong:

n = [3, 5, 7]

def list_function(x):
for i in range(0, len(x)):
x[i] = x[i] * 2
return x

print list_function(n)


#4

Are you on this exercise?: https://www.codecademy.com/en/courses/python-beginner-nzzVa/2/3

If so, you actually should not be using a loop, because you only need to change one item in the list, namely the item at index 1, to which you should add 3. The code you currently have may have come from a different exercise, in which you needed to change every item in the list.


#5

Thank you I have sorted it I was looking at the wrong section for help and that is why i kept getting it wrong!

Thank you


#6

Good - glad it is working now. :smiley:


#7