Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to re-assign items in a list in Python?

I want to re-assign each item in a list in Python.

In [20]: l = [1,2,3,4,5]
In [21]: for i in l:
   ....:     i = i + 1
   ....:     
   ....:     

But the list didn't change at all.

In [22]: l
Out[22]: [1, 2, 3, 4, 5]

I want to know why this happened. Could any body explain the list iterating in detail? Thanks.

like image 275
zfz Avatar asked Dec 21 '25 10:12

zfz


2 Answers

You can't do it like that, you are merely changing the value binded to the name i. On each iteration of the for loop, i is binded to a value in the list. It is not a pointer in the sense that by changing the value of i you are changing a value in the list. Instead, as I said before, it is simply a name and you are just changing the value that name refers to. In this case, i = i + 1, binds i to the value i + 1. So you aren't actually affecting the list itself, to do that you have to set it by index.

>>> L = [1,2,3,4,5]
>>> for i in range(len(L)):
        L[i] = L[i] + 1

>>> L
[2, 3, 4, 5, 6]

Some pythonistas may prefer to iterate like this:

for i, n in enumerate(L): # where i is the index, n is each number
    L[i] = n + 1

However you can easily achieve the same result with a list comprehension:

>>> L = [1,2,3,4,5]
>>> L = [n + 1 for n in L]
>>> L
[2, 3, 4, 5, 6]

For more info: http://www.effbot.org/zone/python-objects.htm

like image 104
jamylak Avatar answered Dec 23 '25 22:12

jamylak


This is because of how Python handles variables and the values they reference.

You should modify the list element itself:

for i in xrange(len(l)):
  l[i] += 1
like image 44
unwind Avatar answered Dec 23 '25 22:12

unwind



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!