In the world of Python programming, a seemingly small distinction can yield significant consequences. When it comes to manipulating variables, difference between a = a+b and a += b in Python
“ may appear subtle, but it packs a powerful punch. In a previous article, we explored the assignment operators in Python and how they perform similar functions in most contexts. For instance, we saw that while adding two integers, โa=a+bโ (which is called the simple assignment operation) and โa+=bโ (which is called the augmented assignment operation) give the same results.
However, the two styles of assignment operators differ in the way they are implemented in Python. Today, we will discuss the internal implementation of the assignment operators by comparing and analyzing the results produced by the augmented assignment operation โa+=bโ and the simple assignment operation โa=a+bโ in Python.ย
The differences
Let us look at the following code example, in which we will examine how even though the final results using both types of assignments may seem identical, they are, in fact, different.ย
Using simple assignment โa = a+bโ:
CODE:
#Initializing two lists
list1 = [1,2,3,4,5];
list2 = [6,7,8];
#getting ID of list 1 before appending
list1_id_before_appending = id(list1);
print("Using simple assignment:");
# append list2 to list 1 using simple assignment
list1 = list1 + list2;
#getting ID of list 1 after appending
list1_id_after_appending = id(list1);
#printing the lists and IDs
print(list1);
print("ID of list 1 before appending: ", list1_id_before_appending);
print("ID of list 1 after appending: ", list1_id_after_appending);
OUTPUT:
Using simple assignment: [1, 2, 3, 4, 5, 6, 7, 8] ID of list 1 before appending:ย 22655314109760 ID of list 1 after appending:ย 22655313231104 |
In the above code, we initialized 2 lists, list1 and list2. We stored the initial ID of list1 for reference. Then, we appended list2 to list1 using the simple assignment operator.ย
We again stored the ID of new list1 in a variable and printed the results.ย
As we can observe, list1 displayed expected values on printing. However, the ID of list1 changed after we appended it with list2.ย
This proves that a new list was created with updated values, and its reference was stored in the variable list1.ย
Let us now execute the same code using the augmented assignment operation:
Using augmented assignment operation โa+=bโ
CODE:
#Initializing two lists
list1 = [1,2,3,4,5];
list2 = [6,7,8];
#getting ID of list 1 before appending
list1_id_before_appending = id(list1);
print("Using augmented assignment:");
# append list2 to list 1 using augmented assignment operation
list1 += list2;
#getting ID of list 1 after appending
list1_id_after_appending = id(list1);
#printing the lists and IDs
print(list1);
print("ID of list 1 before appending: ", list1_id_before_appending);
print("ID of list 1 after appending: ", list1_id_after_appending);
OUTPUT:
Using augmented assignment: [1, 2, 3, 4, 5, 6, 7, 8] ID of list 1 before appending:ย 23336110675264 ID of list 1 after appending:ย 23336110675264 |
We followed the same coding procedure as in the previous example. We initialized 2 lists, list1 and list2 and stored the initial ID of list1 for reference. Then, we appended list2 to list1 using an augmented assignment.
We again stored the ID of new list1 in a variable and printed the results.ย
We can see that the ID of the list1 remains unchanged, even after appending it with list2. This means that instead of creating a new list object and then storing its reference in list1, the augmented assignment operator modified the list1 in place and appended it with list2.ย
What is the internal working of simple vs. augmented assignment operator?
When we use the simple assignment, using the syntax:
variable = expression
Python calculates the value of the expression on the right hand side of the assignment operator, creates a new object to store the value, and assigns the object’s reference to the variable on the left.ย
Thus, we can say that the variable on the left is now pointing to a new memory location, that stores the value of the expression on the right.ย
However, this changes when we use the augmented assignment, using the syntax:
variableย $= expression
Augmented assignments work in a dynamic fashion. Python performs the intended operation, and mutates the object pointed by the variable on the left in-place. Thus, no new objects are created, and the final value of the expression is stored in the same memory location.
To summarise, simple assignment creates a new object and stores its reference to the variable on the left, whereas augmented assignment modifies the original object in-place.
Now, you would hope that this behavior may not affect your life as a programmer, but thatโs not the case. Let us examine the following code sample:
CODE:
#Initializing a list
list1 = [1,2,3,4,5];
#storing its reference in two other variables
list2 = list1;
list3 = list1;
#modifying list2 and list3
list2 = list2 + [6,7,8]; #creates a new object and stores in list2
list3 += [10,11,12]; #modifies the object pointed by list3
#printing the lists
print(list1);
print(list2);
print(list3);
Faced difficulties in understanding the code? No need to fret, you can hire CodingZap experts for your Python homework help.
OUTPUT:
[1, 2, 3, 4, 5, 10, 11, 12] [1, 2, 3, 4, 5, 6, 7, 8] [1, 2, 3, 4, 5, 10, 11, 12] |
In the above code, we initialized list1 with the first 5 natural numbers, and copied itsย reference in list2 and list3.ย
We appended 3 numbers at the end of list2, using the simple assignment operator. The simple assignment operator creates a new object and stores the new reference to the variable on the left, i.e., list2. Thus, list2 loses its reference to the list object pointed by list1, and doesnโt modify it.ย
However, to append 2 integers at the end of list3, we used the augmented assignment operator. Augmented assignment operator modifies the list object pointed by list3 in-place, instead of creating a new object.ย Since list1 pointed to the same object as list3, printing the values of list1 prints the newly modified list.ย
This behavior is also evident in other mutable data structures like sets, byte-arrays, deque etc. Using augmented assignment will modify these data structures in-place, whereas using simple assignment will create new objects.ย
The similarities
The augmented and simple assignment assignment operators however work the same on immutable types, such as ints, floats etc. Let us verify this using code sample:
CODE:
#Initializing an integer
a = 10;
print("Original ID:");
print(id(a));
# modifying value using simple assignment
a = a+10;
print("After simple assignment:");
print(id(a));
# modifying values usin augemented assignment
a += 10;
print("After augmented assignment:");
print(id(a));
OUTPUT:
Original ID: 9801536 After simple assignment: 9801856 After augmented assignment: 9802176 |
As can be observed from the above code example, the reference of โaโ changed after every modification, irrespective of the type of assignment used. We can thus conclude that a new object is created, every time an immutable data type is modified.ย
Which one should you prefer? Read Below
Since the simple assignment creates a new object every time we modify it, it takes longer time and is inefficient when compared to the augmented assignment.ย
When comparing the time and space complexities of the two operators:
Simple assignment:
Time Complexity:
O(n) where n is the size of the list being concatenated.
Space Complexity:
O(1) since the modification happens in-place without creating a new list.
Augmented assignment:
Time Complexity:
O(n) where n is the combined size of the lists being concatenated.
Space Complexity:
O(n) since a new list is created with combined elements.
We must, therefore, use the augmented assignment operations whenever possible, improving code efficiency and memory usage. Particularly with large datasets, these distinctions can offer significant advantages to the programmer.ย
Not so intuitive (but powerful) concatenations
The โ+=โ concatenation operator also works on other iterables, which can be concatenated at the end of a list. An iterable is any Python object capable of returning its members one at a time, permitting it to be iterated over in a for-loop.
The โ+=โ operator concatenates these iterables (by looping each value one-by-one) at the end of the list.ย
On the other hand, the same concatenations are not possible with the simple assignment operator.ย
The reason for this design is that in Python, โ+=โ is an augmented assignment operator. It’s designed to modify mutable objects in place, extending them with the elements from another iterable. This is possible for mutable objects like lists, sets, bytearrays, and deques because they can be modified without creating a new object.
In contrast, + is a binary operator for concatenation. When used with certain types like lists, sets, bytearrays, and deques, it creates a new object by combining the elements of the operands. This is the default behavior for + with these types.
Let us now solidify our understanding with the help of code:
CODE:
#Initializing a list of integers
list = [1,2,3];
print(list)
# Concatenating a string using +=
list += "Hello";
#list = list + "World"; #TypeError: can only concatenate list (not "str") to list
print(list)
# Concatenating a set using +=
set= {"This", "is", "fun"};
list += set;
#list = list + set; #TypeError: can only concatenate list (not "set") to list
print(list)
# Concatenating a tuple using +=
tuple = ("Python", "is", "great");
list += tuple;
#list = list + tuple; #TypeError: can only concatenate list (not "tuple") to list
print(list)
# Concatenating a dictionary using +=
dict = {"First Name": "John", "Last Name": "Doe" };
list += dict;
#list = list + dict; #TypeError: can only concatenate list (not "dict") to list
print(list)
# Concatenating a list returned from a function
def get_numbers():
return [4, 5, 6];
list += get_numbers(); #This will concatenate the list in-place
list = list + get_numbers(); #This will concatenate the list by creating a new object
print(list);
OUTPUT:
[1, 2, 3] [1, 2, 3, ‘H’, ‘e’, ‘l’, ‘l’, ‘o’] [1, 2, 3, ‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘fun’, ‘This’, ‘is’] [1, 2, 3, ‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘fun’, ‘This’, ‘is’, ‘Python’, ‘is’, ‘great’] [1, 2, 3, ‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘fun’, ‘This’, ‘is’, ‘Python’, ‘is’, ‘great’, ‘First Name’, ‘Last Name’] [1, 2, 3, ‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘fun’, ‘This’, ‘is’, ‘Python’, ‘is’, ‘great’, ‘First Name’, ‘Last Name’, 4, 5, 6, 4, 5, 6] |
In the above code sample, we concatenated various data structures, namely, string, set, tuple, dictionary, and even a list returned from a function using the โ+=โ concatenation operator.ย
- String is appended byte-by-byte at the end of the list.ย
- The set is appended at the end of the list, however, the order of elements is not preserved, because set is an unordered data structure.
- All the elements of the tuple are appended at the end of the list.ย
- Concatenating a dictionary shows interesting results, as only the keys of the dictionary are appended at the end of the list.ย
For all these data structures, we cannot do the concatenation using simple assignment, as it will throw a type error.ย
When appending a list returned from a function, we can concatenate using both, simple and augmented operator. However, as is the nature of these operators, augmented operator concatenates in-place, while simple assignment operator creates a new list for concatenation.ย
We can thus see that augmented operators, and specially the concatenation operator โ+=โ are powerful tools in Python programming, and must be leveraged by programmers to write efficient code.ย
Conclusion
In this article, we examined the difference between the simple assignment operation โa=a+bโ and the augmented assignment operation โa+=bโ. We observed and verified through code samples that augmented assignment modifies the object in-place, whereas simple assignment creates a new object for modification. This is also established that this behavior is not evident in immutable objects like ints and floats. We also witnessed the power of the concatenation operator โ+=โ with some code samples. At the end, we rightly concluded that one must use the augmented assignment whenever possible.ย