×

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 PyMOTW

The cmd module comprises one class of the general public, Cmd, meant for command processors such interactive shells and other command interpreters as a foundation class. It utilises readline as...

3 minutes read.

Python JSON Schema

Python-jsonschema JSON: JSON stands for JavaScript Object Notation. It is a text-based format that represents structured data and can be used to interchange data among various applications. This is self-defining language...

5 minutes read.

Python String strip() method

Python String strip() method The string. strip() method in Python removes any leading (spaces at the beginning) and trailing (spaces at the end) characters (space is the default leading character to...

1 minute read.

Python set()

Python set() Class The set() class in Python returns a new set object, optionally with elements taken from iterable.  Syntax class set([iterable]) Parameter iterable : This parameter represents a sequence, collection or an iterator object Return This function returns a...

1 minute read.

Python Empty Tuple

How to Create an Empty Tuple Tuple A tuple is a data structure used to store non-homogeneous data elements. These non-homogeneous data elements consist of integer data type, character data type, String...

3 minutes read.

Python Tkinter Tutorial

What is Tkinter? Tkinter is GUI library of Python. When we integrated Tinkter with Python, it provides an easy and quick way to develop GUI applications. It provides the Tk GUI...

14 minutes read.

Isodate Python

Python Programming Language Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

3 minutes read.

Text detection using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

4 minutes read.

Python Program to Print Sum of all Elements in an Array

Python program to print sum of all elements in an array A set of objects stored in contiguous memory locations is referred to as an array. The concept is to keep...

2 minutes read.

Python String isdigit() method

Python String isdigit() method The string.isdigit() method returns a boolean value true if all characters in the string are digits else for any other value it returns false. Syntax string.isdigit() Parameter NA Return This method returns a...

2 minutes read.

Anaconda python 3 installation for windows 10

If you are a problem solver and like to solve programming questions, the anaconda distribution for python could be one of the best options to use and solve problems in...

3 minutes read.

Python Modules

Python Modules The Python module is a collection of definition and statements. It can contain functions, classes, and variables.  Combining the related code into a module makes the code easier to understand and use....

5 minutes read.

Python Break Statement

In Python, loops are used to automate and repeat processes in an effective manner. However, there may be occasions when you wish to entirely exit the loop, skip an iteration,...

2 minutes read.

Math Module in Python

In this article, you are going to learn everything in detail about the “ math “ module in Python. We can normally work with general operations using python without importing or...

16 minutes read.

Application to Search Installed Application using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

4 minutes read.

Copying a file from one folder to Another with Python

In this article, we shall discuss copying a file from one folder to another using python functions. A file is a collection of data or information stored on a computer....

3 minutes read.

Creating Tables using Python MySQL

In this article, we are going to learn how to create tables in databases using Python MySQL. Introduction to Tables: Generally, databases are used in order to store the information in the...

9 minutes read.

Python vs Java

There are a lot of programming languages out there, and every day, a new programming language is developing in some parts of the world. Each programming language is a mixture...

5 minutes read.

Parameter Passing in Python

In Python, when we characterize capabilities with default values for specific boundaries, it is said to have its contentions set as a possibility for the client. Clients can either pass their...

3 minutes read.

Event Key in Python

Python Programming Language: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

3 minutes read.