Operators in Python used to make a lot of operations on different values and variables like Arithmetic operations(Addition, Subtraction, etc.), Logical operations(AND, OR, etc.), and a lot of other operations.

Table of Contents:

Python Operators Explained

Arithmetic Operators

These operators are mainly used in performing different mathematical operations(Addition, Subtraction, Multiplication, Division, and some more).

The “+” operator

This allows us to add two variables or more and give us the summed value of these variables. Let’s see the following example:

Code:

a = 5
b = 10
c = a + b
print(c)

Output:

15

Explanation:

Simply the variable c has the summed value of the variables a & b after adding them.

The “-” operator

This allows us to subtract two or more variables and gives us the result of this operation. Let’s see the following example:

Code:

a = 5
b = 10
c = b - a
print(c)

Output:

5

Explanation:

Same as in the Addition operation the variable c holds the subtracted value of the variables b & a after subtracting them.

The “*” operator

This one is used in multiplying several variables or values together. Let’s check the following example:

Code:

a = 5
b = 10
c = a * b * 3
print(c)

Output:

150

Explanation:

You can see here that this operator helped us multiplying the variables a & b and the value 3 together.

The “/” & “//” operators

Both operators perform the same operation which is dividing variables and values, but the double backslash rounds the result to the smaller whole number(floor). Let’s explain this by an example:

Code:

a = 5
a = 5
b = 11
c = b / a
d = b // a
print(d)

Output:

2.2
2

Explanation:

As you can see both operators performed the same operation(division), however, the double backslash operator rounded the number to the floor value which in this example is 2.

The “%” operator

This operator helps us find the remainder of dividing two variables or values together. Let’s see the following example:

Code:

a = 6
b = 12
c = 13
d = b % a
e = c % a
print(d)
print(e)

Output:

0
1

Explanation:

As you can see the result of d is equal to zero because there is no remainder when you divide 12 by 6, however, the result of d is equal to one as this is the remainder when you divide 13 by 6.

The “**” operator

This operator helps us perform the power operation, it returns the first variable raised to the power of the second variable. Let’s see the following example:

Code:

a = 2
b = 3
c = a ** b
print(c)

Output:

8

Comparison, or Relational Operators

These kinds of operators help us to compare operands and values. They always return True or False, depending on the condition.

The “>” operator

The greater than the operator and it returns True if and only if the left value or operand is greater than the right one. Let’s see an example:

Code:

a = 2
b = 3
c = 4
print( c > b)
print( a > b)

Output:

True
False

Explanation:

As you can see when the condition is satisfied in the first comparison the output was True, on the other hand when the left operand was less than the right one it returned False.

The “<” operator

The less than an operator and it only returns True if the left value is less than the right value. Let’s see an example:

Code:

a = 2
b = 3
c = 4
print( b < c)
print( b < a)

Output:

True

False

The “==” & “!=” operators

The “==” is the Equal to the operator and it only returns True if both values are equal. On the contrary the “!=” is the Not Equal to the operator and it only returns True if both values are not equal. Let’s see an example:

Code:

a = 2
b = 2
c = 4
print(a == b)
print(a == c)
print(a != c)
print(a != b)

Output:

True

False

True

False

Explanation:

As you can see the “==” operator only returns True when both operands are equal and false otherwise. And the opposite with the “!=” operator.

The “ >=” operator

This one only returns True if the left operand is equal to or greater than the right one. Let’s see an example:

Code:

a = 2
b = 2
c = 4
print(a >= b)
print(a >= c)

Output:

True
False

The “<=” operator

It only returns True if the left operand is less than or equal to the right one. Let’s see an example:

Code:

a = 2
b = 3
c = 4
print(a <= b)
print(c <= a)

Output:

True
False

Logical Operators

These operators are used to compare two or more conditions within a statement.

The “and” operator

Same as the logical AND, it only returns True if the two operands are True. Let’s see an example:

Code:

a = 10
b = 12
c = 15
print( a < b and c > b)
print ( a > b and c > b)

Output:

True
False

Explanation:

The first print statement returns True because both conditions of the and are True. But the second print statement returns False because the first condition is False as the value of a is not greater than b.

The “or” operator

Not like the and operator, the or operator is like the logical OR so only one condition needs to be True. Let’s see an example:

Code:

a = 10
b = 12
c = 15
print ( a > b or c > b)

Output:

True

Explanation:

However the first condition is not true but the second one is, you can find the print statement returned True as the second condition is still True.

The “not” operator

This operator is used to change the returned value, if it’s True it will return False and vice versa. Let’s see an example:

Code:

a = 10
b = 12
c = 15
print (not( a < b and c > b))

Output:

False

Explanation:

However the and operation should return True in this case, but after we put not before it so the returned value is now False.

Bitwise Operators

These operators are used to perform operations and comparisons on binary numbers.

The “&” operator

The AND operator which returns 1 if the two operand bits are 1, otherwise it returns 0. Let’s see an example:

Code:

a = 5 #binary = 0101
b = 8 #binary = 1000
print (a & b)

Output:

0

The “|” operator

The OR operator which returns 1 if any of the two operand bits is 1. Let’s see an example:

Code:

a = 0 #binary = 0000
b = 15 #binary = 1111
print (a | b)

Output:

15

The “^” operator

The XOR operator is unlike the OR, as one of the two operand bits has to be 1 so it returns 1. Let’s see an example:

Code:

a = 5 #binary = 0101
b = 15 #binary = 1111
print (a ^ b)

Output:

10

Explanation:

As you can see it returned 10 which is equal to 1010 in binary.

The “<<” operator

The binary left shift operator where the bits of the left operand moves in the left direction by the number specified in the right operand. Let’s see an example:

Code:

a = 2 # binary = 0010
print (a << 2)

Output:

8

Explanation:

Simply the bits are shifted twice to the left, and it returns 8 which has the binary value 1000.

The “>>” operator

The binary right shift operator where the bits of the left operand moves in the right direction by the number specified in the right operand. Let’s see an example:

Code:

a = 8 # binary =  1000
print (a >> 2)

Output:

2

Explanation:

Simply the bits are shifted twice to the right, and it returns 2 which has the binary value 0010.

Assignment Operators

These kinds of operators are used to perform two operations at the same time like subtraction, addition, division, and then assigning the results of these operations to a variable.

The “=” operator

This is used to assign the right operand or value to the left operand. Let’s see an example:

Code:

a = 5
print(a)
a = 8 
print(a)

Output:

5
8

The “+=” operator

This is used to add the right operand to the left one and assigns the summed value to the left operand. Let’s see an example:

Code:

a = 5
a+=3
print(a)

Output:

8

The “-=” operator

This is used to subtract the second operand from the left one and assigns the subtracted value to the left operand. Let’s see an example:

Code:

a = 5
a-=3
print(a)

Output:

2

The “*=” operator

This operator is used to multiply the left and right operands and assigns the result to the left operand. Let’s see an example.

Code:

a = 5
a*=3
print(a)

Output:

15

The “/=” operator

It’s used to divide the left operand by the right one and assigns the result to the left operand. Let’s see an example:

Code:

a = 15
a/=3
print(a)

Output:

5.0

The “%=” operator

This is used to calculate the remainder of a dividing left operand by the right one and assigns the remainder to the left operand. Let’s see an example:

Code:

a = 15
a%=2
print(a)

Output:

1

The “**=” operator

It’s used to perform the power operation between the two operands and assigns the value to the left operand. Let’s see an example:

Code:

a = 2
a**=3
print(a)

Output:

8

The “&=” operator

This operator performs Bitwise AND operation between two operands and assigns the result to the left operand. Let’s see an example:

Code:

a = 5 #binary = 0101
b = 8 #binary = 1000
a&=b
print(a)

Output:

0

The “|=” operator

It’s used to perform Bitwise OR operation between two operands and assigns the result to the left operand. Let’s see an example:

Code:

a = 0 #binary = 0000
b = 15 #binary = 1111
a|=b
print(a)

Output:

15

The ”^=” operator

This operator performs a Bitwise XOR operation between two operands and assigns the result to the left operand. Let’s see an example:

Code:

a = 5 #binary = 0101
b = 15 #binary = 1111
a^=b
print(a)

Output:

10

The “<<=” operator

This operator makes a Bitwise left shift on the left operand by the value of the right operand and assigns the result to the left operand. Let’s see an example:

Code:

a = 2 # binary =  0010
a<<=2
print(a)

Output:

8

The “>>=” operator

This operator makes a Bitwise right shift on the left operand by the value of the right operand and assigns the result to the left operand. Let’s see an example:

Code:

a = 8 # binary =  1000
a>>=2
print(a)

Output:

2

Python Operation Module

Python offers a module to use the python operations. At first look, Python’s operator module may appear uninteresting. However, it includes a plethora of operator functions for arithmetic and binary operations and a few conveniences and auxiliary functions. They may not appear very useful, but with only a handful of these functions, the user may code faster, more concisely, more readable, and more functionally.

The majority of the module comprises functions that wrap/emulate basic Python operators like +, or not. It may not be immediately evident why the user needs or wants to use any of them when the operator is available, so let’s first discuss some of the use cases for all of these functions.

def apply(op, x, y):
    return op(x, y)

from operator import mul
apply(mul, 3, 7)
# 21

Python’s operators (+, -,…) are not functions and hence cannot be passed straight to functions. Instead, you can use the operator module’s version. Of course, the user might easily design a wrapper function to accomplish this, but who wants to write a function for each arithmetic operator? As an added plus, this enables a more functional style of programming.

The most significant reason to utilize an operator module is to improve readability. It is a matter of personal preference, and if the user frequently uses lambda expressions, it may be more natural to use them. It is more readable to use functions in the operator module rather than lambdas. For example, consider the following.

(lambda x, y: x ^ y)(7, 10)

from operator import xor
xor(7, 10)

Finally, unlike lambdas, operator module functions are chosen, which means they can be saved and retrieved later. It may not appear particularly useful, but it is required for distributed and parallel computing, which requires transmitting functions between processes.

MethodCaller

Methodcaller is another function from the operator module that is worth noticing. This function is to invoke a method on an object by passing its name as a string:

from operator import methodcaller

methodcaller("rjust", 12, ".")("some text")
# "...some text"

column = ["data", "more data", "other value", "another row"]
[methodcaller("rjust", 12, ".")(value) for value in column]
# ["........data", "...more data", ".other value", ".another row"]

In the preceding example, the user effectively uses methodcaller to call “some text.” rjust(12, “.”) is a function that right-justifies a string to a length of 12 characters using the character as the fill character.

Using this function makes more sense when the user has a string name for the desired method and wishes to repeatedly send the same parameters to it, as in the second example above.

The following code is a more practical example of methodcaller usage. In this scenario, the user feeds lines from a text file to the map function while also passing it the required method – in this case, strip – which strips whitespaces from each line. Furthermore, the user passes that to a filter, which removes any empty lines (empty lines are empty strings that are not true, so they get removed by the filter).

from operator import methodcaller

with open(path) as file:
    items = list(filter(None, map(methodcaller("strip"), file.read().splitlines())))
    print(items)