×

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

a += b in Python doesn't always behave the same way as a = a + b; the same operands can produce different outcomes depending on the circumstances. But we must delve deeply into the operation of variables to comprehend why they exhibit diverse behaviours. These operators are convenient ways to add or subtract values from a variable without having to use an intermediate variable. For example, if we want to add two numbers together and store the result in a new variable, we will write:

firstn = firstn + secondn
# But we may just write: if we wish to use the += operator instead
firstn += secondn

To combine two numbers, use the += operator. The variable to the left of the += symbol will hold the sum as a consequence of the addition. In this example, the variable x is used to store the outcome of adding y to x.

But the addition assignment is always not true in all cases and to understand that why this is not equal we need to get into depth into the topic of working and using of variables.

Creating a New Variable:

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

Output:

id of a :  11094592  Value :  10

By Updating and Changing the Variable:

m = 5  # Giving a variable a value creates a new object.
print(" id of m : ", id(m) ," Value : ", m  )
m = m + 10 # An object is created when a variable's value is changed.
print(" id of m : ", id(m) ," Value : ", m  )
m += 10 # An object is created when a variable's value is changed.
print(" id of m : ", id(m) ," Value : ", m  )

Output:

id of m:  11096592  Value :  5
id of m:  11093912 Value:  15
id of m:  11091232 Value:  25

Because each time we create or alter an int, float, char, or string, a new object is formed and its reference is assigned to the appropriate variable. Whereas in the list type this is not able to observe.

m = [0, 1, 2] # m is given the reference to this array after it is stored in memory.
print("id of m: ",id(m) , "Value : ", m )
a = a + [4, 3] Similarly, this will behave by storing data in memory and assigning a variable a reference.
print("id of m: ",id(m) , "Value : ", m )
m += [6, 5]
print("id of m: ",id(m) , "Value : ", m )
# However, this will now provide a new ref. this will change the current object instead, so
# Every other variable that points to a will likewise experience changes.

Output:

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

Now we understand why a = a + b can occasionally differ from a += b.

l1 = [6, 7, 5, 4, 3, 2, 1]
l2 = list1
l1 += [1, 2, 3, 4] # changing the value of the current reference
print(l1)
print(l2) 
# The value of the variable list2, which is pointing to list1, is changed on line 4 #since it was modified without generating a new object.

Output:


6, 7, 5, 4, 3, 2, 1, 1, 2, 3, 4
6, 7, 5, 4, 3, 2, 1, 1, 2, 3, 4
l1 = [6, 5, 4, 3, 2, 1]
l2 = l1
l1 = l1 + [1, 2, 3, 4,7, 8, 9]
# List 1's contents match those of 
#the preceding programme, 
#however List 2's contents differ.
print(l1)
print(l2)

Output:

6, 5, 4, 3, 2, 1, 1, 2, 3, 4,7, 8, 9
6, 5, 4, 3, 2, 1

The expression list1 += [1, 2, 3, 4, 7, 8, 9] extends the list while keeping "l1" and "l2" as references to the same list. This is known as an in-place modification.

listing 1 = listing 1 + [1, 2, 3, 4, 7, 8, 9] generates a new list, modifies "l1" to refer to it, and leaves "l2" referring to the previous list.


Related Topics

Python range() function

Python range() function The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number. Syntax range(stop)        or range(start, stop[, step]) Parameter start: It is...

1 minute read.

Python Dictionary copy() method

Python Dictionary copy() method The dictionary.copy () method in Python returns a copy of the specified dictionary. Syntax dictionary.copy () Parameter NA Return None Example 1 # Python program explaining # the dictionary.copy() method # initialising the dictionary ...

1 minute read.

Assertion Errors and Attribute Errors in Python

Assertion Error in Python In Python, the assert condition is used to continue the execution if the given statement displays true. If the assert statement displays false, it raises Assertion Error...

3 minutes read.

How to Install Pandas in Python?

Pandas is a library created in Python for handling and analyzing data. Pandas provides a variety of procedures and data structures for manipulating time series and numerical data.  Pandas is...

3 minutes read.

Bar Plot in Python

A bar chart or bar graph displays categorical data using rectangular bars with heights or lengths proportionate to the values for the data distributed in the dataset. In a bar...

16 minutes read.

Anytree Python

Python's anytree module is frequently used within data science-related software. Anytree has a Tolerant License, a Construct File that is public, no errors, no risks, and excellent support. One may...

3 minutes read.

Composition in Python

Composition in Python Composition is one of the important concepts of Object-oriented programming (OOPs). Composition basically enables us for creating complex types objects by combining other types of objects in the...

6 minutes read.

Python Syntax Error Invalid Syntax

Python is renowned for its simple and direct syntax. However, we might come across some things that Python doesn't allow if we are learning Python for the very first time or if...

14 minutes read.

How to Iterate a List in Python

As we know, a List is one of the four unique data structures available in Python; in this article, we will deep dive into understanding iterating through a list and...

3 minutes read.

Spotify API in Python

The application programming interface is referred to as API. In essence, an API serves as a layer of communication or, as the name suggests, an interface that enables systems to...

3 minutes read.

Python NewLine

In python, a new line character denoted by "\n" is known as an escape character or escape sequence, and it will force the cursor to change its position to the next...

6 minutes read.

Python lock

Before understanding the concept of Python-lock we need to understand what kind if condition we require to implement the locks in Python. Let us start with multithreading and its implementation...

5 minutes read.

How to Make an App with Python

In this age of mobiles, rapid mobile application development has got a lot of traction. Moreover, app developers are high in demand because of the increase in digitization. Generally, Python is...

4 minutes read.

What is Python compiler GDB?

The source code of one programming language is converted into machine code, bytecode, or another programming language by a compiler, a specialised software. A compiler is a tool that converts high-level...

3 minutes read.

Python Tutorial

Python tutorial is a widely used programming language which helps beginners and professionals to understand the basics of Python programming easily. Python is a high-level, easy, interpreted, general-purpose, and dynamic programming...

19 minutes read.

Django vs NodeJS

Django and NodeJS are open-source frameworks used to develop web applications. Both Django and NodeJS are cross-platform and robust technology used for developing versatile web applications and mobile applications. Django Django is...

2 minutes read.

Python Decorator

Python Decorator: A Decorator is an interesting feature of Python that helps the user design patterns and insert a new functionality to an existing object without making any modifications in...

6 minutes read.

Python Read Excel file

Python Read Excel file Excel is the spreadsheet application for Window, which is developed by Microsoft. The Excel stores data in the tabular form. It provides easy access to analyze and maintain the...

3 minutes read.

SKLearn Clustering

These are ml methods thatare responsible for detecting patterns and the similarities within the data.The clustering methods are unsupervised.Here the data is clustered to form groups with the help of...

3 minutes read.

How to check the version of the Python Interpreter?

As we all know what an interpreter is, and how important it is. We should also be aware of the fact that it is important to have knowledge of the...

2 minutes read.