About Inplace operator in Python

In this tutorial, we will learn about the Inplace operator in Python.

Python provides various methods to perform inplace operations. Inplace operation means the computation and the assignment is done in a single statement.

Let’s take an example,

a+=b is equivalent to a=operator.iadd(x,y)

Inplace operator in Python

Inplace operation is an operation that changes the content of a given algebra directly. That is, it changes in a single line without making a copy. The operations which do this operation is called an Inplace operator.

Let’s discuss some of the important inplace operations in python.

iadd(a,b) 

This function takes two arguments. This is one of the inplace operators in Python. iadd() function performs the addition operation and assigns the value. iadd() performs the operation which is same as a+=b.

Here, assigning is not performed in case of immutable data types like Strings, Numbers, and Tuples.

import operator
x=operator.iadd(5,10)
print("value after using iadd() is:")
print(x)

output:

value after using iadd() is:
15

iconcat(a,b)

This function also takes two arguments. It is a function which concatenates one string with another string at the end.

import operator
x=operator.iadd("code","speedy")
print("string after using iconcat() is:")
print(x)

output:

string after using iconcat() is:
codespeedy

Let’s see another example,

import operator
x="code"
y="speedy"
z=operator.iadd(x,y)
print("string after using iconcat() is:")
print(z)

output:

string after using iconcat() is:
codespeedy

isub(a,b)

This isub() function performs the subtraction operation and assigns the value. isub() performs the operation which is the same as a-=b operation. As same as in iadd(), assignment of value is not done in case of immutable data types like Strings, Numbers, and Tuples.

import operator
x=operator.isub(10,5)
print("value after using isub() is:")
print(x)

output:

value after using isub() is:
5

imul(a,b)

This function performs a multiplication operation and then assign the value. This imul() performs an operation that is the same as a*=b.

import operator
x=operator.imul(10,5)
print("value after using imul() is:")
print(x)

output:

value after using imul() is:
50

itruediv(a,b)

itruediv() function performs the division operation and then assign the value. It performs an operation that is the same as a/=b. That is, it gives quotient after dividing the two numbers.

import operator
x=operator.itruediv(10,5)
print("value after using itruediv() is:")
print(x)

output:

value after using itruediv() is:
2.0

imod(a,b)

This function gives the remainder after dividing the given two numbers and assign the value. imod() performs the operation which is the same as a%=b.

import operator
x=operator.imod(10,5)
print("value after using imod() is:")
print(x)

output:

value after using imod() is:
0

Also read:

Leave a Reply