Home > Backend Development > Python Tutorial > Why Does Python's = Operator on Lists Produce Unexpected Shared-State Behavior?

Why Does Python's = Operator on Lists Produce Unexpected Shared-State Behavior?

Linda Hamilton
Release: 2024-12-14 17:08:18
Original
867 people have browsed it

Why Does Python's  = Operator on Lists Produce Unexpected Shared-State Behavior?

Unexpected Behavior of = Operator on Lists

The = operator in Python exhibits unexpected behavior when operating on lists, as demonstrated in the following code snippet:

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)
Copy after login

Output:

[1, 2]
[1, 2]
Copy after login

The = operator seems to affect every instance of the class, while foo = foo bar behaves as expected.

This behavior stems from the underlying implementation of the = operator. It first attempts to call the iadd special method, which is intended for in-place addition and modifies the object it acts on. If iadd is unavailable, it falls back to the add special method, which returns a new object.

In the case of lists, only add is defined, which returns a new list. Therefore, when = is used on a list, it creates a new list instead of mutating the existing list. This explains why f and g share the same bar list in the above example.

The = operator behaves differently for mutable objects, where it modifies them in-place through the iadd method. For immutable objects like strings and integers, only add is available, resulting in the creation of a new object.

To summarize:

  • = uses iadd if defined, modifying the object in-place.
  • If iadd is not defined, = falls back to __add__, creating a new object.
  • For mutable objects, = modifies the object in-place.
  • For immutable objects, = creates a new object.

The above is the detailed content of Why Does Python's = Operator on Lists Produce Unexpected Shared-State Behavior?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template