Skip to content

Why does x += 1 behave differently with integers vs lists in Python? #164843

Discussion options

You must be logged in to vote

Excellent question! This is one of Python's most confusing concepts, and you've discovered the difference between mutable and immutable objects.

What's really happening:

The key insight: += calls different methods

# For integers (immutable):
x += 1  # Actually calls: x = x.__add__(1)  -> creates new object

# For lists (mutable):  
x += [4]  # Actually calls: x.__iadd__([4])  -> modifies existing object
Let's trace through your examples:
Example 1 - Integers:
pythonx = 5        # x points to integer object 5
y = x        # y also points to the same integer object 5
x += 1       # Creates NEW integer object 6, x now points to it
             # y still points to the original integer object 5

Replies: 2 comments

Comment options

You must be logged in to vote
0 replies
Answer selected by Istituto-freudinttheprodev
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Programming Help Discussions around programming languages, open source and software development
2 participants