Python: LISTS AND FUNCTIONS Modifying each element in a list in a function


#1

Hi guys I’m currently stuck with a problem. I am not sure what’s wrong with my code.

  1. 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.

I initially typed the following:

n = [3, 5, 7]

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

double_list(n)

which turns out was wrong as I did not return the new list even though the output was correct and came as:
6
10
14

but after adding return as below:

n = [3, 5, 7]

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

double_list(n)

The only output is 6

and this message pops up “double_list([0, 1]) returned 0 instead of [0, 2]”

Pls help. Also my indentations were correct its just not showing up on the posted version for some reason.


#2

Do not print inside the function. Be sure to return the list, not just a single element.


#3

Hi mtf, when I type out:

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

I am taking out each index from the range 0 to the end index on list x and multiplying it by 2 right? from what I know so far it’s looping through each item on said list. so when i add return x as below I’m returning the doubled list right?

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

so why does my output for the following code comes as: [6,5,7] with an error “double_list([0, 1]) returned [0, 1] instead of [0, 2]”

following code:

n = [3, 5, 7]

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

double_list(n)

#4

As suspected, this is inside the loop when it shouldn’t be.


#5

Get it now! Thanks loads.


#6

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