Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python assign values to list elements in loop

Is this a valid python behavior? I would think that the end result should be [0,0,0] and the id() function should return identical values each iteration. How to make it pythonic, and not use enumerate or range(len(bar))?

bar = [1,2,3]
print bar
for foo in bar:
    print id (foo)
    foo=0
    print id(foo)
print bar

output:

[1, 2, 3]
5169664
5169676
5169652
5169676
5169640
5169676
[1, 2, 3]
like image 452
Chris Avatar asked Dec 19 '13 17:12

Chris


People also ask

How do you assign a value to a list in a loop in Python?

First of all, you cannot reassign a loop variable—well, you can, but that won't change the list you are iterating over. So setting foo = 0 will not change the list, but only the local variable foo (which happens to contain the value for the iteration at the begin of each iteration).


1 Answers

First of all, you cannot reassign a loop variable—well, you can, but that won’t change the list you are iterating over. So setting foo = 0 will not change the list, but only the local variable foo (which happens to contain the value for the iteration at the begin of each iteration).

Next thing, small numbers, like 0 and 1 are internally kept in a pool of small integer objects (This is a CPython implementation detail, doesn’t have to be the case!) That’s why the ID is the same for foo after you assign 0 to it. The id is basically the id of that integer object 0 in the pool.

If you want to change your list while iterating over it, you will unfortunately have to access the elements by index. So if you want to keep the output the same, but have [0, 0, 0] at the end, you will have to iterate over the indexes:

for i in range(len(bar)):
    print id(bar[i])
    bar[i] = 0
    print id(bar[i])
print bar

Otherwise, it’s not really possible, because as soon as you store a list’s element in a variable, you have a separate reference to it that is unlinked to the one stored in the list. And as most of those objects are immutable and you create a new object when assigning a new value to a variable, you won’t get the list’s reference to update.

like image 150
poke Avatar answered Oct 03 '22 17:10

poke