Home >Backend Development >Python Tutorial >How Does Python's = Operator Differentially Affect Lists Depending on __iadd__ and __add__?
How the = Operator Operates on Lists in Python
The = operator in Python exhibits unexpected behavior when applied to lists. This behavior is attributed to the distinction between the iadd and add special methods.
iadd vs add
Behavior on Lists
When = is used on a list with an iadd method, the list is modified in place. If iadd is not defined, add is invoked, resulting in a new list.
Example
Consider the following code:
class foo: bar = [] def __init__(self, x): self.bar += [x] class foo2: bar = [] def __init__(self, x): self.bar = self.bar + [x] f = foo(1) g = foo(2) print(f.bar) print(g.bar) f.bar += [3] print(f.bar) print(g.bar) f.bar = f.bar + [4] print(f.bar) print(g.bar) f = foo2(1) g = foo2(2) print(f.bar) print(g.bar)
Output
[1, 2] [1, 2] [1, 2, 3] [1, 2, 3] [1, 2, 3, 4] [1, 2, 3] [1] [2]
Explanation
Conclusion
The behavior of = on lists depends on whether it calls iadd or add__. In-place modification occurs with __iadd__, while __add creates a new list.
The above is the detailed content of How Does Python's = Operator Differentially Affect Lists Depending on __iadd__ and __add__?. For more information, please follow other related articles on the PHP Chinese website!