Modifying each element in a list in a function


#1

Hi, I am stuck on the exercise “Modifying each element in a list in a function”, could some one help me please?

The instructions:
Create a function called double_list that takes a single argument x (which will be a list) and multiplies each element by 2 and returns that list. Use the existing code as a scaffold.

The Hint:
You can place the code on lines 3 - 5 inside a function definition. You will need to change the n[i]s in the for loop to x[i]. Make sure to indent properly!

Error message I get:
double_list([0, 1]) returned [0, 1] instead of [0, 2]

My code:

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)



#2

here:

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

why do you use len(n), if we add the second function call from the instructions:

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)
print double_list([0, 1])

we can see it go wrong


#3

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