Modifying each element in a list in a function


My for loop doesn't seem to be iterating through each item in the list the first item gets doubled, the other two don't:

"Oops, try again. double_list([0, 1]) returned [0, 1] instead of [0, 2]"

I expect all items in the list to get doubled, thank you in advance

n = [3, 5, 7]

def double_list(x):
    for i in range(0, len(x)):
        x[i] = x[i] * 2
# Don't forget to return your new list!
        return x

print double_list(n)


You should return x outside the function, so Remove one indentation before your return statement.

        x[i] = x[i] * 2
 # Don't forget to return your new list!
    return x


Wow, I was stuck on that for way too long. Thank you for your prompt reply!


We get what you mean, but this is not correct if taken literally. ... outside of the loop is more to the point.


Oops, sorry. I was negligent for a little.


Thanks. It makes sense now that I look at it. If the return is put inside the loop, the loop essentially is ended and the result is printed. 3 comes in and 6 comes out as the result. The loop ends before it has a chance to put the next number from the list in the loop. With it being outside the loop the result is the loop runs until all the list numbers are exhausted, after which we ask it to return the result of running the list.


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