Modifying each element in a list in a function


#1

def list_function(n):
return n[1] + 3

n = [3, 5, 7]

n[1] = list_function(n)

print list_function

the program shows an error, what did i do wrong? I do not exactly understand how to do this. Please reply ASAP, thanks.


#2

Oops, i copied the wrong code, i meant:

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

n = [3, 5, 7]

print double_list(n)


#3

protip: If you want quick replies then explain what's wrong and format your code and don't say "asap". Make it appealing instead of telling others that you're top priority.


#4

n = [3, 5, 7]

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

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

print double_list(n)


#5

:open_mouth:


#6

you need check your "return x" of tabs


#7

I don't know if you are still struggling with this: take the return x out of the for loop (i.e. get rid of one of the indentations).


#8

I'm confused that it's just 'return x' and not return `double_list(x)`- actually my first attempt was return double_list(n).

Can you explain why it is just return x and not either of the other two?


#10

if you will retutn double_list(n) or double_list(X) it will call double _list function repeteadly. Hence,it will go into infinite loop. Thus, we have to usereturn X only.


#11

Below, is an answer.

x = [3, 5, 7]

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

print double_list(x)