Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Difference between x = x+1 and x += 1 [duplicate]

Tags:

python

In Python, is there any difference (semantics, efficiency, etc.) between writing x = x+1 and x += 1?

like image 961
John Avatar asked Oct 15 '12 23:10

John


People also ask

What is the difference between x += 1 and x =+ 1?

Difference between x++ and x=x+1 in Java. In x++, it increase the value of x by 1 and in x=x+1 it also increase the value of x by 1. But the question is that both are same or there is any difference between them.

What does x += 1 do in Python?

With x = x + 1 , the interpreter will treat it like x = x. __add__(1) , while x += 1 will be x = x. __iadd(1) , which can be much more efficient because it doesn't necessarily need to make a copy of x . x += 1 actually becomes x = x.

What is the difference between i += 1 and i i 1 in Python?

i+=1 does the same as i=i+1 there both incrementing the current value of i by 1. Do you mean "i += 1"? If so, then there's no difference.

What is the difference between i i 1 and i += 1 in a for loop?

The difference is that one modifies the data-structure itself (in-place operation) b += 1 while the other just reassigns the variable a = a + 1 .


1 Answers

Yes. Depending on how the class of x is coded, the short form has the option to modify x in-place, instead of creating a new object representing the sum and rebinding it back to the same name. This has an implication if you have multiple variables all referring to the same object - eg, with lists:

>>> a = b = []
>>> a += [5]
>>> a
[5]
>>> b
[5]
>>> a = a + [5]
>>> a
[5, 5]
>>> b
[5]

This happens because behind the scenes, the operators call different magic methods: + calls __add__ or __radd__ (which are expected not to modify either of their arguments) and += tries __iadd__ (which is allowed to modify self if it feels like it) before falling back to the + logic if __iadd__ isn't there.

like image 185
lvc Avatar answered Oct 14 '22 18:10

lvc