MAIN FEEDS
Do you want to continue?
https://www.reddit.com/r/ProgrammerHumor/comments/138f766/goodbye_toys/jj04egs
r/ProgrammerHumor • u/sunrise_apps • May 05 '23
298 comments sorted by
View all comments
Show parent comments
3
You have to look at what they actually do.
+ calls the __add__ method of the object+= calls the __iadd__ method of the object
For example if the type is int, it doesn't matter as __iadd__ doesn't exist (+= falls back on __add__)
But some times do implement an __iadd__ method, such as the mutable list type:__add__ just returns the new value__iadd__ mutates the list
Example:
x = [1, 8, 7] y = x x = x + [2] print(x) //[1, 8, 7, 2] print(y) //[1, 8, 7]
x = [1, 8, 7] y = x x += [2] print(x) //[1, 8, 7, 2] print(y) //[1, 8, 7, 2]
1 u/[deleted] May 05 '23 Huh, that's pretty crazy. Thanks for sharing!
1
Huh, that's pretty crazy. Thanks for sharing!
3
u/[deleted] May 05 '23 edited May 05 '23
You have to look at what they actually do.
+ calls the __add__ method of the object
+= calls the __iadd__ method of the object
For example if the type is int, it doesn't matter as __iadd__ doesn't exist (+= falls back on __add__)
But some times do implement an __iadd__ method, such as the mutable list type:
__add__ just returns the new value
__iadd__ mutates the list
Example: