Why Identical Python Lines Behave Differently: Mutation vs. Rebinding Explained
In Python, variables are names bound to objects rather than containers holding values, a distinction that explains surprising behavior when working with mutable and immutable types. Operations on objects fall into two categories: mutation, which modifies the object in place so all names pointing to it see the change, and rebinding, which points a name to a new object without affecting others. The += operator can act as either mutation or rebinding depending on whether the object implements __iadd__, which is why the same syntax behaves differently on lists versus integers. Shallow copies add another layer of complexity, as copying an outer list still leaves inner objects shared between the original and the copy. Understanding whether an operation mutates an object or rebinds a name is key to diagnosing most unexpected behavior in Python programs.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.
Discussion (0)
Log in to join the discussion and vote.
Log in