python assign values to list elements in loop

后端 未结 4 2137
醉酒成梦
醉酒成梦 2020-11-27 06:27

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

4条回答
  •  无人及你
    2020-11-27 07:01

    you actually didnt change the list at all. the first thing for loop did was to assign bar[0] to foo(equivalent to foo = bar[0]). foo is just an reference to 1. Then you assign another onject 0 to foo. This changed the reference of foo to 0. But you didnt change bar[0]. Remember, foo as a variable, references bar[0], but assign another value/object to foo doesn't affect bar[0] at all.

提交回复
热议问题