- Daily Dose of Data Science
- Posts
- Manipulating Mutable Objects In Python Can Get Confusing At Times
Manipulating Mutable Objects In Python Can Get Confusing At Times
a = a + b and a += b are not the same!
Did you know that with mutable objects, “𝐚 +=” and “𝐚 = 𝐚 +” work differently in Python? Here's why.
Let's consider a list, for instance.
When we use the = operator, Python creates a new object in memory and assigns it to the variable.
Thus, all the other variables still reference the previous memory location, which was never updated. This is shown in Method1.py above.
But with the += operator, changes are enforced in-place. This means that Python does not create a new object and the same memory location is updated.
Thus, changes are visible through all other variables that reference the same location. This is shown in Method2.py above.
We can also verify this by comparing the 𝐢𝐝() pre-assignment and post-assignment.
With “𝐚 = 𝐚 +”, the 𝐢𝐝 gets changed, indicating that Python created a new object. However, with “𝐚 +=”, 𝐢𝐝 stays the same. This indicates that the same memory location was updated.
👉 See what others are saying about this post on LinkedIn: Post Link.
👉 If you love reading this newsletter, feel free to share it with friends!
Find the code for my tips here: GitHub.
Reply