💦 FULL SET: /library/operator.html - Uncensored 2025
9.9. operator — Standard operators as functions¶
The operator module exports a set of efficient functions corresponding to
the intrinsic operators of Python. For example, operator.add(x, y) is
equivalent to the expression x+y. The function names are those used for
special class methods; variants without leading and trailing __ are also
provided for convenience.
The functions fall into categories that perform object comparisons, logical operations, mathematical operations, sequence operations, and abstract type tests.
The object comparison functions are useful for all objects, and are named after the rich comparison operators they support:
-
operator.lt(a, b)¶ -
operator.le(a, b)¶ -
operator.eq(a, b)¶ -
operator.ne(a, b)¶ -
operator.ge(a, b)¶ -
operator.gt(a, b)¶ -
operator.__lt__(a, b)¶ -
operator.__le__(a, b)¶ -
operator.__eq__(a, b)¶ -
operator.__ne__(a, b)¶ -
operator.__ge__(a, b)¶ -
operator.__gt__(a, b)¶ Perform “rich comparisons” between a and b. Specifically,
lt(a, b)is equivalent toa < b,le(a, b)is equivalent toa <= b,eq(a, b)is equivalent toa == b,ne(a, b)is equivalent toa != b,gt(a, b)is equivalent toa > bandge(a, b)is equivalent toa >= b. Note that unlike the built-incmp(), these functions can return any value, which may or may not be interpretable as a Boolean value. See Comparisons for more information about rich comparisons.New in version 2.2.
The logical operations are also generally applicable to all objects, and support truth tests, identity tests, and boolean operations:
-
operator.not_(obj)¶ -
operator.__not__(obj)¶ Return the outcome of
notobj. (Note that there is no__not__()method for object instances; only the interpreter core defines this operation. The result is affected by the__nonzero__()and__len__()methods.)
-
operator.truth(obj)¶ Return
Trueif obj is true, andFalseotherwise. This is equivalent to using theboolconstructor.
-
operator.is_(a, b)¶ Return
a is b. Tests object identity.New in version 2.3.
-
operator.is_not(a, b)¶ Return
a is not b. Tests object identity.New in version 2.3.
The mathematical and bitwise operations are the most numerous:
-
operator.div(a, b)¶ -
operator.__div__(a, b)¶ Return
a / bwhen__future__.divisionis not in effect. This is also known as “classic” division.
-
operator.index(a)¶ -
operator.__index__(a)¶ Return a converted to an integer. Equivalent to
a.__index__().New in version 2.5.
-
operator.inv(obj)¶ -
operator.invert(obj)¶ -
operator.__inv__(obj)¶ -
operator.__invert__(obj)¶ Return the bitwise inverse of the number obj. This is equivalent to
~obj.New in version 2.0: The names
invert()and__invert__().
-
operator.truediv(a, b)¶ -
operator.__truediv__(a, b)¶ Return
a / bwhen__future__.divisionis in effect. This is also known as “true” division.New in version 2.2.
-
operator.xor(a, b)¶
