+ 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)
10 Antworten
+ 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.
+ 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.
+ 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.
+ 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👍🏼
+ 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.
+ 3
Ian18, I would definitely like to take a closer look at that overload of __add__! 😜
+ 2
there is no why, is a matter of prefference, if you like x=x+2 then you can use that
+ 1
Thanks
0
puton- язык программирования