Modifying each element in a list in a function(what am I missing?)

When you ask a question, don’t forget to include a link to the exercise or project you’re dealing with!

https://www.codecademy.com/courses/learn-python/lessons/lists-and-functions/exercises/modifying-each-element-in-a-list-in-a-function?action=resume_content_item

Hi everyone!

I’m having trouble with lists! I have written the code exactly* as in the solution(I think) but I cant for the life of me figure out why my code doesnt work, and the code, using the solution, does.

here is my code:

n = [3, 5, 7]

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

print double_list(n)

It doubles the first item in the list(item 0) but all the other items retain their old value; as to why, I havent been able to figure that out. I’m sure its something simple that im missing but regardless I would like to understand what is wrong with my code.

I’m also recieving the following error message at the bottom of the editor when I run the program:

double_list([0, 1]) returned [0, 1] instead of [0, 2]; as I dont know exactly what it means or why its happening, I require your insights!

Sincerely Daniel

ps: thanks!

If you want to have the best chances of getting a useful answer quickly, make sure you follow our guidelines about how to ask a good question. That way you’ll be helping everyone – helping people to answer your question and helping others who are stuck to find the question and answer! :slight_smile:

1 Like

return x ends the function. Meaning the loop only runs once.

1 Like

What he said. Python depends on indentation (tabs, spaces) so this:

for i in range(len(x)):
    [code]
    return x

is different than this:

for i in range(len(x)):
    [code]
return x

Code #1 will run once because a return statement ends the loop completely. Code #2 will run all the times you want it to and then end the function.
*edit: clarity

1 Like