Python for 循环是否按引用工作? [英] Do Python for loops work by reference?
问题描述
当在 Python 中使用 for
循环迭代列表中的项目时,改变 item
(下面)会改变 items
?
When using a for
loop in Python to iterate over items in a list, will changing item
(below) change the corresponding item in items
?
for item in items:
item += 1
items 中的每个 item 会递增还是保持与循环之前相同?
Will each item in items be incremented or remain the same as before the loop?
[注意:我会对 Python 2.7 和 3.x 感兴趣]
[Note: I would be interested in Python 2.7 and 3.x]
推荐答案
不,Python 中的变量不是指针.
No, variables in Python are not pointers.
它们改为引用堆上的对象,并且分配给变量不会更改引用的对象,而是变量.变量和对象就像绑在气球上的标签;分配将标签重新绑定到不同的气球.
They refer to objects on a heap instead, and assigning to a variable doesn't change the referenced object, but the variable. Variables and objects are like labels tied to balloons; assignment reties the label to a different balloon instead.
见这个我以前的回答 进一步探索气球和标签的想法.
See this previous answer of mine to explore that idea of balloons and labels a bit more.
也就是说,一些对象类型实现了特定的就地添加行为.如果对象是可变的(气球本身可以改变),那么就地添加可以被解释为突变而不是赋值.
That said, some object types implement specific in-place addition behaviour. If the object is mutable (the balloon itself can change), then an in-place add could be interpreted as a mutation instead of an assignment.
因此,对于整数,item += 1
与 item = item + 1
实际上相同,因为整数是不可变的.您必须创建一个新的整数对象并将item
标签绑定到该新对象上.
So, for integers, item += 1
is really the same as item = item + 1
because integers are immutable. You have to create a new integer object and tie the item
label to that new object.
另一方面,列表是可变的,lst += [other, items]
被实现为一个 lst.__iadd__([other, items])
并且改变了 lst
气球本身.赋值仍然发生,但它是同一个对象的重新赋值,因为 .__iadd__()
方法只返回 self
而不是一个新对象.我们最终将标签重新绑在同一个气球上.
Lists on the other hand, are mutable and lst += [other, items]
is implemented as a lst.__iadd__([other, items])
and that changes the lst
balloon itself. An assignment still takes place, but it is a reassigment of the same object, as the .__iadd__()
method simply returns self
instead of a new object. We end up re-tying the label to the same balloon.
循环只是在每次迭代时为您提供对列表中下一项的引用.它不允许您更改原始列表本身(这只是另一组气球标签);相反,它为您包含的每个项目提供一个新标签.
The loop simply gives you a reference to the next item in the list on each iteration. It does not let you change the original list itself (that's just another set of balloon labels); instead it gives you a new label to each of the items contained.
这篇关于Python for 循环是否按引用工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!