13. Modifying each element in a list in a function


#1



13. Modifying each element in a list in a function

I believe I got the formula correctly but still find it hard to understand why I need to write for i in range(0,len(x)) instead of for i in x? Is range necessary for the formula to recognise that I am using a list?


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)


#2

you need to use range() because this will give you indexes, so you can manipulate the list. If you use for i in x, i will be read only values from the list, which means you are unable to modify the original list, instead you would have to create a new list


#3

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