Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python list mutation (for in loop vs range(len))

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
like image 529
Solaxun Avatar asked Apr 10 '26 10:04

Solaxun


1 Answers

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.

like image 62
nitishagar Avatar answered Apr 12 '26 22:04

nitishagar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!