Modifying each element in a list in a function


#1

n = [3, 5, 7]

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

print double_list(n)

Oops, try again. double_list([0, 1]) returned [0, 1] instead of [0, 2]

Can anyone tell me what is wrong with this ?


#2

Try this,

def double_list(item):
    return [x * 2 for x in item]

OR

EDITED FOR CLARITY:

def double_list(item):
    doubled = []
    for x in item:
        doubled.append(x * 2)
    return doubled

#3

Nope. That came up with a bunch of errors.
Traceback (most recent call last):
File "python", line 18, in
File "python", line 15, in double_list
AttributeError: 'function' object has no attribute 'append'


#4

However, this worked:

def double_list(item):
return [x * 2 for x in item]

thank you very much


#5

Oops, I named the function and the parameter the same thing lol.

Change the parameter name and it will work.


#7