We often use
x += y instead of
x = x + y. So, are they same or different? Let’s Find it here.
[1, 2, 3] [1, 2, 3]
[1, 2, 3] [1, 2]
So here we find that both codes are almost similar but still there are difference in the outputs. So the reason behind this is that for many types of objects,
x += y will modify the object referred to by
x in-place, whereas
x = x + y will create a new object and reassign
x to it. This distinction is important if you still have another reference to the object somewhere like in this case
another_a is another reference to the object.
However, many objects such as numbers and strings are “immutable” – they can’t be modified in-place – and for those objects,
x += y and
x = x + y will typically do exactly the same thing. But if you write your own class you can customize what
+= do when used with objects of that class, and you can make them do completely different things if you really want to.
- Difference between 'and' and '&' in Python
- Difference between == and is operator in Python
- Difference between continue and pass statements in Python
- Python - Difference between sorted() and sort()
- Difference between Yield and Return in Python
- Difference between Method Overloading and Method Overriding in Python
- Difference between dir() and vars() in Python
- What is the difference between Python's Module, Package and Library?
- Python | Using variable outside and inside the class and method
- 10 Essential Python Tips And Tricks For Programmers
- Python | Float type and its methods
- How to assign values to variables in Python and other languages
- Namespaces and Scope in Python
- Statement, Indentation and Comment in Python
- Download and Install Python 3 Latest Version
- break, continue and pass in Python
- Primary and secondary prompt in Python
- Check the equality of integer division and math.floor() of Regular division in Python
- How to print to stderr and stdout in Python?
- String to Int and Int to String in Python
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.