Difference Between x = x + y and x += y in Python
We often use x += y instead of x = x + y. So, are they same or different? Let’s Find it here.
Example 1:
x = [1, 2] another_x = x y = [3] x += y print(x) print(another_x) |
Output:
[1, 2, 3] [1, 2, 3]
Example 2:
x = [1, 2] another_x = x y = [3] x = x + y print(x) print(another_x) |
Output:
[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 + and += do when used with objects of that class, and you can make them do completely different things if you really want to.
Example 3:
x = "12345"another_x = x y = "67890" x += y print(x) print(another_x) |
Output:
1234567890 12345
Example 4:
x = "12345"another_x = x y = "67890" x = x + y print(x) print(another_x) |
Output:
1234567890 12345
Recommended Posts:
- Python set operations (union, intersection, difference and symmetric difference)
- Difference between 'and' and '&' in Python
- Python Set | difference()
- Difference between C and Python
- Difference between Python and C#
- Difference between Python and C++
- Difference between various Implementations of Python
- Python | Difference between two lists
- Difference between Python and JavaScript
- Difference Between '+' and 'append' in Python
- Difference between == and is operator in Python
- Difference Between Python and Bash
- Difference between dir() and vars() in Python
- Difference between Python and Java
- Python | Difference between iterable and iterator
- Difference between List and Dictionary in Python
- Python | Triple list difference
- Python | Difference in keys of two dictionaries
- Python - Sort Dictionary by Value Difference
- Python | Difference Between List and Tuple
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.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.


