w3resource

Python Operators

Operators and Operands

In computer programming languages operators are special symbols which represent computations, conditional matching etc. The values the operator uses are called operands.

c = a + b
Here a and b are called operands and '+' is an operator

Python supports following operators.

Contents:

Operator: Commands

Module of functions that provide the functionality of operators.

from operator import add, sub, mul, truediv, floordiv, mod, pow, neg, abs
from operator import eq, ne, lt, le, gt, ge
from operator import and_, or_, not_
from operator import itemgetter, attrgetter, methodcaller
import operator as op
sorted_by_second = sorted(<collection>, key=op.itemgetter(1))
sorted_by_both   = sorted(<collection>, key=op.itemgetter(1, 0))
product_of_elems = functools.reduce(op.mul, <collection>)
LogicOp          = enum.Enum('LogicOp', {'AND': op.and_, 'OR' : op.or_})
last_el          = op.methodcaller('pop')(<list>)

Python Arithmetic Operators

Operator Name Example Result
+ Addition x+y Sum of x and y.
- Subtraction x-y Difference of x and y.