Open In App

Python | a += b is not always a = a + b

Last Updated : 29 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In Python, a += b doesn’t always behave the same way as a = a + b, the same operands may give different results under different conditions. But to understand why they show different behaviors you have to deep dive into the working of variables. before that, we will try to understand the difference between Python Variable and List Reference in Python.

Difference Between Variable and List Reference

Here, we will see the difference between variable and list reference.

Creating New Variable

In this example, we have created a new variable and will see about its reference. Here, value 10 gets stored in memory and its reference gets assigned to a. 

Python3




a = 10
print(" id of a : ", id(10) ," Value : ", a  )


Output

id of a :  11094592  Value :  10
a 
or 

Modifying The Variable

In this example, we are modifying the variable and then comparing the reference after using + and += operators. Whenever we create or modify int, float, char, or string they create new objects and assign their newly created reference to their respective variables.

Python3




a = 10  # Assigning value to variable creates new object
print(" id of a : ", id(a) ," Value : ", a  )
 
a = a + 10 # Modifying value of variable creates new object
print(" id of a : ", id(a) ," Value : ", a  )
   
a += 10 # Modifying value of variable creates new object
print(" id of a : ", id(a) ," Value : ", a  )


Output

id of a :  11094592  Value :  10
id of a :  11094912  Value :  20
id of a :  11095232  Value :  30

But the same behavior is not seen in the list. In the below example, we can see that the reference remain same when we use + and += operator in the list.

Python3




a = [0, 1] # stores this array in memory and assign its reference to a
print("id of a: ",id(a) , "Value : ", a )
 
a = a + [2, 3] # this will also behave same store data in memory and assign ref. to variable
print("id of a: ",id(a) , "Value : ", a )
 
a += [4, 5]
print("id of a: ",id(a) , "Value : ", a )
 
#But now this will now create new ref. instead this will modify the current object so
# all the other variable pointing to a will also gets changes


 Output

id of a:  140266311673864 Value :  [0, 1]
id of a:  140266311673608 Value :  [0, 1, 2, 3]
id of a:  140266311673608 Value :  [0, 1, 2, 3, 4, 5]  

Python | a += b is not always a = a + b

In Python, a+=b is not always a=a+b. We will see this aspect with the help of som examples.

Example: In this example, we can see that list2 which is pointing to list1 gets changes without creating a new object. We can see that the content of list1 and list2 are same. It is because we are using a+=b.

Python3




list1 = [5, 4, 3, 2, 1]
list2 = list1
list1 += [1, 2, 3, 4] # modifying value in current reference
 
# as on line 4 it modify the value without creating new object
# variable list2 which is pointing to list1 gets changes
print(list1)
print(list2)


Output

[5, 4, 3, 2, 1, 1, 2, 3, 4]
[5, 4, 3, 2, 1, 1, 2, 3, 4]

Example: In this example, we can see that the contents of list1 are same as above but the content of list 2 are different. It is because we are using a=a+b in this example.

Python3




list1 = [5, 4, 3, 2, 1]
list2 = list1
list1 = list1 + [1, 2, 3, 4]
 
# Contents of list1 are same as above
# program, but contents of list2 are
# different.
print(list1)
print(list2)


Output

[5, 4, 3, 2, 1, 1, 2, 3, 4]
[5, 4, 3, 2, 1]



Previous Article
Next Article

Similar Reads

Python | Number of elements to be removed such that product of adjacent elements is always even
Given an array of N integers. The task is to eliminate the number of elements such that in the resulting array the product of any two adjacent values is even. Examples: Input : arr[] = {1, 2, 3} Output : 0 Input : arr[] = {1, 3, 5, 4, 2} Output : 2 Remove 1 and 3. Approach: The product of 2 numbers is even if any one of them is even. This means for
2 min read
List Methods in Python | Set 1 (in, not in, len(), min(), max()...)
List methods are discussed in this article. 1. len() :- This function returns the length of list. List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1] print(len(List)) Output: 10 2. min() :- This function returns the minimum element of list. List = [2.3, 4.445, 3, 5.33, 1.054, 2.5] print(min(List)) Output: 1.054 3. max() :- This function returns the maximum eleme
2 min read
Filter Pandas dataframe in Python using 'in' and 'not in'
The in and not in operators can be used with Pandas DataFrames to check if a given value or set of values is present in the DataFrame or not using Python. The in-operator returns a boolean value indicating whether the specified value is present in the DataFrame, while the not-in-operator returns a boolean value indicating whether the specified valu
3 min read
Python Program that Displays the Letters that are in the First String but not in the Second
Python program to display the letters in the first string but not in the second can be done by taking two sets and subtracting them. As sets support the difference operator, one set could contain the letters of the first string and another set could contain the letters of the second string and when subtracted we could obtain the desired result. Exa
5 min read
Python Set | Check whether a given string is Heterogram or not
Given a string S of lowercase characters. The task is to check whether a given string is a Heterogram or not using Python. A heterogram is a word, phrase, or sentence in which no letter of the alphabet occurs more than once. Input1: S = "the big dwarf only jumps"Output1: YesExplanation: Each alphabet in the string S is occurred only once.Input2: S
3 min read
Python | Make pair from two list such that elements are not same in pairs
Given two lists, the task is to create pairs of elements (pairs can be repeated) from two list such that elements are not same in pairs. Examples: Input : list1 = [100, 20, 30, 400] list2 = [400, 2, 30] Output: [[100, 400], [100, 2], [100, 30], [20, 400], [20, 2], [20, 30], [30, 400], [30, 2], [400, 2], [400, 30]] Input: list1 = [10,20,30,40] list2
2 min read
Python | range() does not return an iterator
range() : Python range function generates a list of numbers which are generally used in many situation for iteration as in for loop or in many other cases. In python range objects are not iterators. range is a class of a list of immutable objects. The iteration behavior of range is similar to iteration behavior of list in list and range we can not
2 min read
Python Program to Check if String is Empty or Not
Python strings are immutable and have more complex handling when discussing their operations. Note that a string with spaces is actually an empty string but has a non-zero size. This article also discussed that problem and the solution to it. Let's see different methods of Check if String is Empty Python. Example Input:[" "]Output: YesExplanation:
8 min read
Python | Check if list is sorted or not
The sorted operation of list is essential operation in many application. But it takes best of O(nlogn) time complexity, hence one hopes to avoid this. So, to check if this is required or not, knowing if list is by default sorted or not, one can check if list is sorted or not. Lets discuss various ways this can be achieved. Method #1 : Naive method
5 min read
Python program to check if a given string is Keyword or not
Given a string, write a Python program that checks if the given string is keyword or not. Keywords are reserved words which cannot be used as variable names.There are 33 keywords in Python programming language.(in python 3.6.2 version) Examples: Input: str = "geeks" Output: geeks is not a keyword Input: str = "for" Output: for is a keyword We can a
3 min read
Practice Tags :
three90RightbarBannerImg