Why does x += 1
behave differently with integers vs lists in Python?
#164843
Answered
by
MatteoMgr2008
Istituto-freudinttheprodev
asked this question in
Programming Help
-
BodyConfusing behavior I discoveredI found something weird about With integers (behaves as expected):def test_int():
x = 5
y = x
x += 1
print(f"x = {x}, y = {y}") # x = 6, y = 5
test_int() # Makes sense - y is unchanged
## With lists (unexpected behavior):
```python
def test_list():
x = [1, 2, 3]
y = x
x += [4]
print(f"x = {x}, y = {y}") # x = [1, 2, 3, 4], y = [1, 2, 3, 4]
test_list() # Wait... why did y change too?!
## Even weirder - this behaves differently:
```python
def test_list_concat():
x = [1, 2, 3]
y = x
x = x + [4] # Using + instead of +=
print(f"x = {x}, y = {y}") # x = [1, 2, 3, 4], y = [1, 2, 3]
test_list_concat() # Now y is unchanged again
## My confusion:
- Why does x += [4] modify the original list that y points to?
- Why does x = x + [4] create a new list instead?
I thought += and = x + were the same thing!
This is really messing with my head. Can someone explain what's actually happening here?
I'm using Python 3.11 and this behavior is consistent across different environments.
### Guidelines
- [X] I have read and understood this category's [guidelines](https://github.com/orgs/community/discussions/51384) before making this post. |
Beta Was this translation helpful? Give feedback.
Answered by
MatteoMgr2008
Jul 2, 2025
Replies: 2 comments
-
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:
|
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
Istituto-freudinttheprodev
-
Thank you so much for the answer! |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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