๐ Python Mistakes Everyone Makes ❌
Day 11: Using += Thinking It Creates a New Object
Many Python beginners assume += always creates a new object.
That’s not always true.
❌ The Mistake
Output:
[1, 2, 3, 4]❌ Why this surprises people?
Because += modifies the object in place for mutable types like lists.
a and b both reference the same list
-
Using += changes the original object
-
Both variables see the change
✅ The Correct Understanding
Output:
[1, 2, 3]Now a and b are different objects.
๐ง Simple Rule to Remember
+= on mutable objects → modifies in place
+= on immutable objects → creates a new object
Example:
✅ Key Takeaway
+= does not always create a new object.
Understanding mutability helps avoid unexpected bugs.


0 Comments:
Post a Comment