Skip to content

Operators in Python

Unleashing the Power of Operators in Python

Operators in Python play a pivotal role in performing various operations on variables and values. They are the building blocks of expressions, allowing you to manipulate data, make comparisons, and control the flow of your programs. In this comprehensive guide, we’ll delve into the diverse world of operators in Python and explore their applications in different contexts.

For example:

operators.py
x = 10 + 5
print(x)
operators.py
x = 10 + 5
print(x)

Output:

command
C:\Users\Your Name> python operators.py
15
command
C:\Users\Your Name> python operators.py
15

Here, ++ is the operator that performs addition. 1010 and 55 are the operands and 1515 is the output of the operation.

In python, we have the following types of operators:

  1. Arithmetic Operators
  2. Comparison (Relational) Operators
  3. Assignment Operators
  4. Logical Operators
  5. Bitwise Operators
  6. Membership Operators
  7. Identity Operators
  8. Operator Precedence
  9. Ternary Operator
  10. Operator Overloading
  11. Operator Functions

Let’s take a closer look at each of these operators.

1. Arithmetic Operators

Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication, etc. They operate on numeric values and return a numeric value as the output.

The following table lists the arithmetic operators in Python:

OperatorDescriptionExample
++Adds two operands or unary plusx + yx + y
--Subtracts right operand from the left or unary minusx - yx - y
**Multiplies two operandsx * yx * y
//Divides left operand by right operandx / yx / y
%%Modulus operatorx % yx % y
****Exponentiation operatorx ** yx ** y
////Floor division operatorx // yx // y

2. Comparison Operators

Comparison operators are used to compare two values. They either return TrueTrue or FalseFalse according to the condition. The following table lists the comparison operators in Python:

OperatorDescriptionExample
====If the values of two operands are equal, then the condition becomes truex == yx == y
!=!=If values of two operands are not equal, then the condition becomes truex != yx != y
>>If the value of the left operand is greater than the value of the right operand, then the condition becomes truex > yx > y
<<If the value of the left operand is less than the value of the right operand, then the condition becomes truex < yx < y
>=>=If the value of the left operand is greater than or equal to the value of the right operand, then the condition becomes truex >= yx >= y
<=<=If the value of the left operand is less than or equal to the value of the right operand, then the condition becomes truex <= yx <= y

3. Logical Operators

Logical operators are used to combine conditional statements. They either return TrueTrue or FalseFalse according to the condition. The following table lists the logical operators in Python:

OperatorDescriptionExample
andandReturns TrueTrue if both statements are truex < 5 and x < 10x < 5 and x < 10
ororReturns TrueTrue if one of the statements is truex < 5 or x < 4x < 5 or x < 4
notnotReverse the result, returns FalseFalse if the result is truenot(x < 5 and x < 10)not(x < 5 and x < 10)

4. Bitwise Operators

Bitwise operators are used to perform bitwise calculations on integers. The following table lists the bitwise operators in Python:

OperatorDescriptionExample
&&Performs bitwise AND on operandsx & yx & y
||Performs bitwise OR on operandsx | yx | y
^^Performs bitwise XOR on operandsx ^ yx ^ y
~~Performs bitwise NOT on operands~x~x
<<<<Performs bitwise left shift on operandsx << yx << y
>>>>Performs bitwise right shift on operandsx >> yx >> y

5. Assignment Operators

Assignment operators are used to assign values to variables. The following table lists the assignment operators in Python:

OperatorDescriptionExample
==Assigns values from the right side operands to the left side operandx = y + zx = y + z
+=+=It adds the right operand to the left operand and assigns the result to the left operandx += yx += y is equivalent to x = x + yx = x + y
-=-=It subtracts the right operand from the left operand and assigns the result to the left operandx -= yx -= y is equivalent to x = x - yx = x - y
*=*=It multiplies the right operand with the left operand and assigns the result to the left operandx *= yx *= y is equivalent to x = x * yx = x * y
/=/=It divides the left operand with the right operand and assigns the result to the left operandx /= yx /= y is equivalent to x = x / yx = x / y
%=%=It takes modulus using two operands and assigns the result to the left operandx %= yx %= y is equivalent to x = x % yx = x % y
**=**=Performs exponential (power) calculation on operators and assigns the result to the left operandx **= yx **= y is equivalent to x = x ** yx = x ** y
//=//=It performs floor division on operators and assigns the result to the left operandx //= yx //= y is equivalent to x = x // yx = x // y
&=&=Performs bitwise AND on operators and assigns the result to the left operandx &= yx &= y is equivalent to x = x & yx = x & y
|=|=Performs bitwise OR on operators and assigns the result to the left operandx |= yx |= y is equivalent to x = x | yx = x | y
^=^=Performs bitwise XOR on operators and assigns the result to the left operandx ^= yx ^= y is equivalent to x = x ^ yx = x ^ y
>>=>>=Performs bitwise right shift on operators and assigns the result to the left operandx >>= yx >>= y is equivalent to x = x >> yx = x >> y
<<=<<=Performs bitwise left shift on operators and assigns the result to the left operandx <<= yx <<= y is equivalent to x = x << yx = x << y

6. Membership Operators

Membership operators are used to test if a sequence is presented in an object. The following table lists the membership operators in Python:

OperatorDescriptionExample
ininReturns TrueTrue if a sequence with the specified value is present in the objectx in yx in y
not innot inReturns TrueTrue if a sequence with the specified value is not present in the objectx not in yx not in y

7. Identity Operators

Identity operators are used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location. The following table lists the identity operators in Python:

OperatorDescriptionExample
isisReturns TrueTrue if both variables are the same objectx is yx is y
is notis notReturns TrueTrue if both variables are not the same objectx is not yx is not y

8. Operator Precedence

Operator precedence is a set of rules that defines the order in which the operators are evaluated in an expression. The following table lists the operator precedence in Python:

OperatorDescription
()()Parentheses
****Exponentiation
~~Bitwise not
**, //, %%, ////Multiplication, Division, Modulus, Floor division
++, --Addition, Subtraction
<<<<, >>>>Bitwise shift operators
&&Bitwise AND
^^Bitwise XOR
||Bitwise OR
====, !=!=, >>, >=>=, <<, <=<=, isis, is notis not, inin, not innot inComparisons, Identity, Membership operators
notnotLogical NOT
andandLogical AND
ororLogical OR

9. Ternary Operator

Ternary operator is also known as conditional operator. It is used to evaluate an expression based on some condition. The following is the syntax of ternary operator in Python:

ternary_operator.py
[on_true] if [expression] else [on_false]
ternary_operator.py
[on_true] if [expression] else [on_false]

Here, expressionexpression is evaluated and if it is TrueTrue, then on_trueon_true is returned otherwise on_falseon_false is returned.

For example:

ternary_operator.py
x = 10
y = 20
big = x if x > y else y
print(big)
ternary_operator.py
x = 10
y = 20
big = x if x > y else y
print(big)

Output:

command
C:\Users\Your Name> python ternary_operator.py
20
command
C:\Users\Your Name> python ternary_operator.py
20

10. Operator Overloading

Operator overloading is a feature in Python that allows the same operator to have different meanings according to the context. For example, the ++ operator will, perform arithmetic addition on two numbers, merge two lists, or concatenate two strings.

In Python, we can redefine or overload most of the built-in operators available in Python. Thus, we can use operators with user-defined types as well.

For example, suppose we have created a class named VectorVector to represent two-dimensional vectors. Let’s overload the ++ operator to perform vector addition.

operator_overloading.py
class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y
 
    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)
 
first = Vector(2, 3)
second = Vector(4, 5)
result = first + second
print(result.x)
print(result.y)
operator_overloading.py
class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y
 
    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)
 
first = Vector(2, 3)
second = Vector(4, 5)
result = first + second
print(result.x)
print(result.y)

Output:

command
C:\Users\Your Name> python operator_overloading.py
6
8
command
C:\Users\Your Name> python operator_overloading.py
6
8

Here, we have overloaded the ++ operator to add two VectorVector objects. The __add__()__add__() method is called when ++ operator is used on VectorVector objects.

Similarly, we can overload other operators as well. The following table lists the operators that can be overloaded in Python:

OperatorMethodDescription
++__add__(self, other)__add__(self, other)Addition
--__sub__(self, other)__sub__(self, other)Subtraction
**__mul__(self, other)__mul__(self, other)Multiplication
//__truediv__(self, other)__truediv__(self, other)Division
%%__mod__(self, other)__mod__(self, other)Modulus
////__floordiv__(self, other)__floordiv__(self, other)Floor Division
****__pow__(self, other)__pow__(self, other)Exponentiation
&&__and__(self, other)__and__(self, other)Bitwise AND
||__or__(self, other)__or__(self, other)Bitwise OR
^^__xor__(self, other)__xor__(self, other)Bitwise XOR
~~__invert__(self)__invert__(self)Bitwise NOT
<<<<__lshift__(self, other)__lshift__(self, other)Bitwise left shift
>>>>__rshift__(self, other)__rshift__(self, other)Bitwise right shift
====__eq__(self, other)__eq__(self, other)Equal to
!=!=__ne__(self, other)__ne__(self, other)Not equal to
<<__lt__(self, other)__lt__(self, other)Less than
>>__gt__(self, other)__gt__(self, other)Greater than
<=<=__le__(self, other)__le__(self, other)Less than or equal to
>=>=__ge__(self, other)__ge__(self, other)Greater than or equal to
+=+=__iadd__(self, other)__iadd__(self, other)Addition
-=-=__isub__(self, other)__isub__(self, other)Subtraction
*=*=__imul__(self, other)__imul__(self, other)Multiplication
/=/=__idiv__(self, other)__idiv__(self, other)Division
%=%=__imod__(self, other)__imod__(self, other)Modulus
//=//=__ifloordiv__(self, other)__ifloordiv__(self, other)Floor Division
**=**=__ipow__(self, other)__ipow__(self, other)Exponentiation
&=&=__iand__(self, other)__iand__(self, other)Bitwise AND
|=|=__ior__(self, other)__ior__(self, other)Bitwise OR
^=^=__ixor__(self, other)__ixor__(self, other)Bitwise XOR
<<=<<=__ilshift__(self, other)__ilshift__(self, other)Bitwise left shift
>>=>>=__irshift__(self, other)__irshift__(self, other)Bitwise right shift
()()__call__(self, other)__call__(self, other)Call operator
[][]__getitem__(self, other)__getitem__(self, other)Index operator
()()__setitem__(self, other)__setitem__(self, other)Index assignment operator
deldel__delitem__(self, other)__delitem__(self, other)Index deletion operator
len()len()__len__(self, other)__len__(self, other)Length operator
str()str()__str__(self, other)__str__(self, other)String conversion operator
repr()repr()__repr__(self, other)__repr__(self, other)Object representation operator
iter()iter()__iter__(self, other)__iter__(self, other)Iteration operator
next()next()__next__(self, other)__next__(self, other)Next iteration operator
reversed()reversed()__reversed__(self, other)__reversed__(self, other)Reverse iteration operator
cmp()cmp()__cmp__(self, other)__cmp__(self, other)Comparison operator
pos()pos()__pos__(self, other)__pos__(self, other)Unary plus
neg()neg()__neg__(self, other)__neg__(self, other)Unary minus
abs()abs()__abs__(self, other)__abs__(self, other)Absolute value
invert()invert()__invert__(self, other)__invert__(self, other)Bitwise NOT
complex()complex()__complex__(self, other)__complex__(self, other)Complex number conversion
int()int()__int__(self, other)__int__(self, other)Integer conversion
long()long()__long__(self, other)__long__(self, other)Long integer conversion
float()float()__float__(self, other)__float__(self, other)Float conversion
oct()oct()__oct__(self, other)__oct__(self, other)Octal conversion
hex()hex()__hex__(self, other)__hex__(self, other)Hexadecimal conversion
index()index()__index__(self, other)__index__(self, other)Conversion to an integer
trunc()trunc()__trunc__(self, other)__trunc__(self, other)Truncation operator
coerce()coerce()__coerce__(self, other)__coerce__(self, other)Coercion
enter()enter()__enter__(self, other)__enter__(self, other)Context management protocol
exit()exit()__exit__(self, other)__exit__(self, other)Context management protocol
hash()hash()__hash__(self, other)__hash__(self, other)Hashing operator
getattr()getattr()__getattr__(self, other)__getattr__(self, other)Attribute access
setattr()setattr()__setattr__(self, other)__setattr__(self, other)Attribute assignment
delattr()delattr()__delattr__(self, other)__delattr__(self, other)Attribute deletion
dir()dir()__dir__(self, other)__dir__(self, other)Attribute query
getattribute()getattribute()__getattribute__(self, other)__getattribute__(self, other)Attribute access
set()set()__set__(self, other)__set__(self, other)Descriptor access
delete()delete()__delete__(self, other)__delete__(self, other)Descriptor deletion
get()get()__get__(self, other)__get__(self, other)Descriptor access

11. Operator Functions

Python provides built-in functions for performing various operations. These functions are called operator functions. For example, operator.add(x, y)operator.add(x, y) is equivalent to x + yx + y.

operator_functions.py
import operator
print(operator.add(10, 20))
operator_functions.py
import operator
print(operator.add(10, 20))

Output:

command
C:\Users\Your Name> python operator_functions.py
30
command
C:\Users\Your Name> python operator_functions.py
30

The following table lists the operator functions in Python:

OperatorFunctionDescription
++operator.add(a, b)operator.add(a, b)Addition
--operator.sub(a, b)operator.sub(a, b)Subtraction
**operator.mul(a, b)operator.mul(a, b)Multiplication
//operator.truediv(a, b)operator.truediv(a, b)Division
%%operator.mod(a, b)operator.mod(a, b)Modulus
////operator.floordiv(a, b)operator.floordiv(a, b)Floor Division
****operator.pow(a, b)operator.pow(a, b)Exponentiation
&&operator.and_(a, b)operator.and_(a, b)Bitwise AND
||operator.or_(a, b)operator.or_(a, b)Bitwise OR
^^operator.xor(a, b)operator.xor(a, b)Bitwise XOR
~~operator.invert(a)operator.invert(a)Bitwise NOT
<<<<operator.lshift(a, b)operator.lshift(a, b)Bitwise left shift
>>>>operator.rshift(a, b)operator.rshift(a, b)Bitwise right shift
====operator.eq(a, b)operator.eq(a, b)Equal to
!=!=operator.ne(a, b)operator.ne(a, b)Not equal to
<<operator.lt(a, b)operator.lt(a, b)Less than
>>operator.gt(a, b)operator.gt(a, b)Greater than
<=<=operator.le(a, b)operator.le(a, b)Less than or equal to
>=>=operator.ge(a, b)operator.ge(a, b)Greater than or equal to
+=+=operator.iadd(a, b)operator.iadd(a, b)Addition
-=-=operator.isub(a, b)operator.isub(a, b)Subtraction
*=*=operator.imul(a, b)operator.imul(a, b)Multiplication
/=/=operator.itruediv(a, b)operator.itruediv(a, b)Division
%=%=operator.imod(a, b)operator.imod(a, b)Modulus
//=//=operator.ifloordiv(a, b)operator.ifloordiv(a, b)Floor Division
**=**=operator.ipow(a, b)operator.ipow(a, b)Exponentiation
&=&=operator.iand(a, b)operator.iand(a, b)Bitwise AND
|=|=operator.ior(a, b)operator.ior(a, b)Bitwise OR
^=^=operator.ixor(a, b)operator.ixor(a, b)Bitwise XOR
<<=<<=operator.ilshift(a, b)operator.ilshift(a, b)Bitwise left shift
>>=>>=operator.irshift(a, b)operator.irshift(a, b)Bitwise right shift
()()operator()operator()Call operator
[][]operator[]operator[]Index operator
()()operator[]operator[]Index assignment operator
deldeloperator[]operator[]Index deletion operator
len()len()operator.len()operator.len()Length operator
str()str()operator.str()operator.str()String conversion operator
repr()repr()operator.repr()operator.repr()Object representation operator
iter()iter()operator.iter()operator.iter()Iteration operator
next()next()operator.next()operator.next()Next iteration operator
reversed()reversed()operator.reversed()operator.reversed()Reverse iteration operator
cmp()cmp()operator.cmp()operator.cmp()Comparison operator
pos()pos()operator.pos()operator.pos()Unary plus
neg()neg()operator.neg()operator.neg()Unary minus
abs()abs()operator.abs()operator.abs()Absolute value
invert()invert()operator.invert()operator.invert()Bitwise NOT
complex()complex()operator.complex()operator.complex()Complex number conversion
int()int()operator.int()operator.int()Integer conversion
long()long()operator.long()operator.long()Long integer conversion
float()float()operator.float()operator.float()Float conversion
oct()oct()operator.oct()operator.oct()Octal conversion
hex()hex()operator.hex()operator.hex()Hexadecimal conversion
index()index()operator.index()operator.index()Conversion to an integer
trunc()trunc()operator.trunc()operator.trunc()Truncation operator
coerce()coerce()operator.coerce()operator.coerce()Coercion
enter()enter()operator.enter()operator.enter()Context management protocol
exit()exit()operator.exit()operator.exit()Context management protocol
hash()hash()operator.hash()operator.hash()Hashing operator
getattr()getattr()operator.getattr()operator.getattr()Attribute access
setattr()setattr()operator.setattr()operator.setattr()Attribute assignment
delattr()delattr()operator.delattr()operator.delattr()Attribute deletion
dir()dir()operator.dir()operator.dir()Attribute query
getattribute()getattribute()operator.getattribute()operator.getattribute()Attribute access
set()set()operator.set()operator.set()Descriptor access
delete()delete()operator.delete()operator.delete()Descriptor deletion
get()get()operator.get()operator.get()Descriptor access

Conclusion

Operators in Python provide a powerful and flexible means of manipulating data, making decisions, and controlling the flow of your programs. Understanding how to use and combine different operators is essential for writing expressive, efficient, and functional code.

As you explore Python programming, experiment with various operators, understand their behaviors, and leverage their capabilities in your projects. Whether you’re performing arithmetic calculations, making logical decisions, or managing data, operators are your allies in creating robust and dynamic Python code.

For more in-depth tutorials and practical examples, check out our resources on Python Central Hub!

Was this page helpful?

Let us know how we did