Daily Dose of Data Science

Share this post

Manipulating Mutable Objects In Python Can Get Confusing At Times

www.blog.dailydoseofds.com

Manipulating Mutable Objects In Python Can Get Confusing At Times

a = a + b and a += b are not the same!

Avi Chawla
Mar 10, 2023
8
Share

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.

Thanks for reading Daily Dose of Data Science! Subscribe for free to learn something new about Python and Data Science every day.

πŸ‘‰ 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!

Share Daily Dose of Data Science


Check out Sourcery, an automated code refactoring tool for Python to make your code more elegant, concise, and pythonic.

Find the code for my tips here:Β GitHub.

I like to explore, experiment and write about data science concepts and tools. You can read my articles on Medium. Also, you can connect with me on LinkedIn.

8
Share
Previous
Next
Comments
Top
New
Community

No posts

Ready for more?

Β© 2023 Avi Chawla
Privacy βˆ™ Terms βˆ™ Collection notice
Start WritingGet the app
SubstackΒ is the home for great writing