In Python, is there any difference (semantics, efficiency, etc.) between writing x = x+1 and x += 1?
In Python, is there any difference (semantics, efficiency, etc.) between writing x = x+1
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Yes. Depending on how the class of
xis 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: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 modifyselfif it feels like it) before falling back to the+logic if__iadd__isn’t there.