Why does this code behave this way?


#1



https://www.codecademy.com/courses/python-beginner-nzzVa/3/2?curriculum_id=4f89dab3d788890003000096

My code returns this error: Oops, try again.
double_list([0, 1]) returned [0, 1] instead of [0, 2]

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)



I realized it was a problem with my indentation.
The console printed out the correct output '[6, 10, 14]' when I submitted my code using the variable n as an argument and indented thus:

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)

Could someone please explain this? Why is the output different for both instances?
I know it's my indentation and I have tried to move on from this but I can't.
Why won't it work the same?


#2

I think "return" is used to end a function, so that is why in the loop when it hit "return". it end the "double_list" function and never go to the second iteration because the function itself already end.


#3

You're a live-saver! Your explanation helped me figure it out.
That bit about

did the trick. I compared both bits of code again and understood exactly why I was getting something different than expected. Thanks.


#4

You are welcome. Glad it help.


#5

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