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 pyth
Yes, the output you got is the ordinary Python behavior. Assigning a new value to foo
will change foo's id, and not change the values stored in bar
.
If you just want a list of zeroes, you can do:
bar = [0] * len(bar)
If you want to do some more complicated logic, where the new assignment depends on the old value, you can use a list comprehension:
bar = [x * 2 for x in bar]
Or you can use map
:
def double(x):
return x * 2
bar = map(double, bar)