why does the below not mutate the passed in list:
def modify(listarg):
for x in listarg:
x=x*2
whereas this does mutate it:
def modify(listarg):
for x in range(len(listarg)):
listarg[x]=listarg[x]*2
The first one just gives you the iterated variable (x), essentially for...in uses built-in iter function. In the second case you actually bind value to list.
for x in listarg:
x=x*2
The code above can be seen as:
i = iter(listarg)
x = i.next() # fetch first value
# this value then you double
# which won't effect the element
For further details you can refer this article.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With