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 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.

Similar Reads

Difference Between Variable and List Reference

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

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

...

Contact Us