Modifying each element in a list in a function


#1




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:

Error:
"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)


#2

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

#3

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


#4

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


#5

Oops, sorry. I was negligent for a little.


#6

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.


#7

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