+ 2

In python, why do we use x+=2 instead of using x=x+2

I already understands how it works but wanted to know how it helps to use x+=2 instead of x=x+2. (Suppose i have already set the value of x to 4)

7th Jun 2019, 11:15 AM
MAW P
MAW P - avatar
10 ответов
+ 9
There is actually a difference between a = a+ b and a += b. If you are doing this on a mutable object (like a list) the first one creates a new object and the second one mutates the original one. Usually this doesn't matter but if you don't know about it, it can be a bug that's very hard to find.
7th Jun 2019, 12:44 PM
Thoq!
Thoq! - avatar
+ 5
x += 1 is supposed to change a value 'in-place' (although it not always happens), while x = x+1 creates a new object in a new memory location and gives it the name x that belonged to that other object/location before.
7th Jun 2019, 11:25 AM
HonFu
HonFu - avatar
+ 4
It's just shorter. Maybe programmers are so lazy. 😂 It could also be useful in some cases when you dont want to use parentheses, because inplace operators' operation precedences are low.
7th Jun 2019, 11:21 AM
Seb TheS
Seb TheS - avatar
+ 3
Well it just makes it more readable. No real reason to waste more space (and its easier to understand with bigger codes) In both cases the result will be 6👍🏼
7th Jun 2019, 11:21 AM
Trigger
Trigger - avatar
+ 3
If you were to use x=x+2 you would create a digital portal to an alternate dimension where everybody is wearing hotdog hats. Also, its about space.
7th Jun 2019, 1:29 PM
Ian18
Ian18 - avatar
+ 3
Ian18, I would definitely like to take a closer look at that overload of __add__! 😜
7th Jun 2019, 1:40 PM
HonFu
HonFu - avatar
+ 2
there is no why, is a matter of prefference, if you like x=x+2 then you can use that
7th Jun 2019, 11:21 AM
Cat Sauce
Cat Sauce - avatar
+ 1
Thanks
7th Jun 2019, 11:22 AM
MAW P
MAW P - avatar
0
puton- язык программирования
7th Jun 2019, 1:12 PM
Никита Бурлаков
Никита Бурлаков - avatar