Modifying each item in a list in a function


#1




Hello, I'm pretty confused as to why this:


Replace this line with your code. 
def double_list(x):
    for i in range(0,len(x)):
        x[i] *=2
    return x


works but this:

def double_list(x):
    for item in x:
        item*=2
    return x

doesn't


#2

because item gets assigned each value in the list (x), you can see this:

for item in [1,2,3,4,5]:
   print item

so in each run of the loop, items gets overwritten where as in your first approach you use the temporary variable (which is now an index) to update an item in the list


#3

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