Skip to content

Python import operator

  • by

The Python operator module is one of the inbuilt modules in Python. By import operator, you can perform various operations and operate two input numbers in a Python program.

The functions provided by the operator module can use various mathematical, relational, logical, and bitwise operations on two input numbers

Functions supplied by the operator module.

MethodSignatureBehaves like
absabs(a)abs(a)
addadd(a,b)a+b
and_and_(a,b)a&b
concatconcat(a,b)a+b
containscontains(a,b)b in a
countOfcountOf(a,b)a.count(b)
delitemdelitem(a,b)del a[b]
delslicedelslice(a,b,c)del a[b:c]
divdiv(a,b)a/b
eqeq(a,b)a==b
floordivfloordiv(a,b)a//b
gege(a,b)a>=b
getitemgetitem(a,b)a[b]
getslicegetslice(a,b,c)a[b:c]
gtgt(a,b)a>b
indexOfindexOf(a,b)a.index(b)
invert, invinvert(a), inv(a)~a
isis(a,b)a is b
is_notis_not(a,b)a is not b
lele(a,b)a<=b
lshiftlshift(a,b)a<<b
ltlt(a,b)a<b
modmod(a,b)a%b
mulmul(a,b)a*b
nene(a,b)a!=b
negneg(a)-a
not_not_(a)not a
or_or_(a,b)a|b
pospos(a)+a
repeatrepeat(a,b)a*b
rshiftrshift(a,b)a>>b
setitemsetitem(a,b,c)a[b]=c
setslicesetslice(a,b,c,d)a[b:c]=d
subsub(a,b)a-b
truedivtruediv(a,b)a/b # "true" div -> no truncation
truthtruth(a)not not a, bool(a)
xor_xor(a,b)a^b

Source: https://www.oreilly.com/library/view/python-in-a/0596100469/ch15s02.html

Python import operator

Simple example code.

import operator

# input numbers from user
x = int(input("Enter first integer number: "))
y = int(input("Enter second integer number: "))

# Adding both input numbers  
add = operator.add(x, y)
print("Addition: ", add)

# Subtracting both input numbers
sub = operator.sub(x, y)
print("Subtraction: ", sub)

# Multiply both input numbers
mul = operator.mul(x, y)
print("Multiplication: ", mul)

# Divide both input numbers
truediv = operator.truediv(x, y)
print("True division: ", truediv)

# floor division
fldiv = operator.floordiv(x, y)
print("Floor division: ", fldiv)

# modulus operation
mod = operator.mod(x, y)
print("Modulus: ", mod)

# power value operation
pow = operator.pow(x, y)
print("Exponentiation: ", pow)

Output:

Python import operator

Here’s a simple example:

import operator

# Sample data
data = [{'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}, {'name': 'Charlie', 'age': 22}]

# Sort the list of dictionaries based on the 'age' key
sorted_data = sorted(data, key=operator.itemgetter('age'))

# Print the sorted data
print(sorted_data)

In this example, operator.itemgetter('age') is used as the key function for sorting the list of dictionaries based on the ‘age’ key.

Comment if you have any doubts or suggestions on this Python operator topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *