Reputation: 23
n = [3, 5, 7]
def double_list(x):
for i in range(0, len(x)):
x[i] = x[i] * 2
return x[i]
print double_list(n)
For some reason this python script is only returning the first item in the list instead of all three when it runs... Can someone please help me?!
Upvotes: 1
Views: 143
Reputation: 3871
to add to the options:
def double_list(x):
return map(lambda num: num*2, x)
print double_list([2, 3, 4])
Upvotes: 0
Reputation: 206707
Change the return
statement so that it is not indented to be part of the for
block.
Return the list instead of an item from the list.
def double_list(x):
for i in range(0, len(x)):
x[i] = x[i] * 2
return x
Upvotes: 3
Reputation:
n = [3, 5, 7]
def double_list(x):
t=[i*2 for i in x]
return t
print (double_list(n))
Another short way for that.
Upvotes: 1
Reputation: 23088
Use a list comprehension instead.
double_list = [ x*2 for x in n ]
Same result, four times shorter, a trillion times more readable.
Upvotes: 5
Reputation: 4035
n = [3, 5, 7]
def double_list(x):
for i in range(0, len(x)):
x[i]*=2
return x
print double_list(n)
Try this.Returning the list, also check how we re-define variables with arithmetical operations.
Upvotes: -4