Python comes with some useful standard operators for performing some basic operations. Some of these operators can be grouped as shown below:
- arithmetic (
+
,-
,*
,/
,%
,//
,**
) - comparison (
==
,!=
,>
,<
,>=
,<=
) - logical (
and
,or
,not
) - assignment (
=
,+=
,-=
,*=
,/=
,%=
,//=
,**=
) - membership (
in
,not in)
- Bitwise(
&
,|
,~
,^
,<<
,>>
)
The operator
module in the standard library provides a functional interface for accessing and using the standard operators. This provides a convenient functionality especially in cases where we want to pass the operator functions as arguments in other functions such as as keys in some higher order functions.
Logical Operations
The module provides functions for performing logical operations for performing boolean operations. The three functions are is_()
, and_ ()
and is_not()
to match the operators is
, not
and is not
, respectively.
Some of the functions are defined with a trailing comma to avoid conflict with the operator keywords under the same name.
Arithmetic Operations
The module provides various functions to match the existing arithmetic operators.
Comparison Operations
There is a function to match each of the rich comparison operators(<
, >
, <=
, >=
, ==
, !=
), ie lt()
, gt()
, le()
, ge()
, eq()
and ne()
, respectively.
Sequence Operations
The module also have functions for performing sequence operations such as, adding elements, searching for elements, accessing elements and removing elements.
Operations on custom objects
User-defined classes can support the operators and the equivalent functions by defining the relevant dunder methods. This is a form of polymorphism also known as operator overloading.
In the above example, we created a custom class with a name Myobj
, we defined the __lt__()
and __add__()
dunder methods so that objects of the class will support the less than and addition operations respectively. We then created two objects of the class and then performed the two operations on them.
All the available functions
The functions provided in the module are as summarized below:
Function |
Usage |
Similar to |
---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|