Python Operators Explained in Detail with Examples


Python

Author: Bashir Alam
Reviewer: Deepak Prasad

When diving into the world of Python programming, understanding Python operators is akin to learning the alphabets of a new language. These operators act as the building blocks for any Python script, playing a critical role in carrying out operations like arithmetic calculations, comparisons, and logical decisions. Not only do they facilitate code execution, but they also make your code more efficient and readable. In this comprehensive guide, we will explore various types of Python operators, how they function, and why they are essential for anyone aspiring to master Python programming.

 

Different Python Operators

Here are the list of Python Operators:

  • Arithmetic Operators
  • Comparison Operators
  • Logical Operators
  • Assignment Operators
  • Augmented Operators
  • Bitwise Operators
  • Identity Operators
  • Membership Operators

We will cover these in detail in next chapters.

 

1. Arithmetic operators in Python

As the name suggests, these operators perform various arithmetic operations and calculations like addition, multiplications, division, etc. They can be used with numerical data types like integers and floats, and some can even be used with strings and lists for operations like concatenation and repetition.

Below is a table that provides a detailed explanation of arithmetic operators in Python.

Operator Description Example Output
+ Addition a = 5; b = 2; print(a + b) 7
- Subtraction a = 5; b = 2; print(a - b) 3
* Multiplication a = 5; b = 2; print(a * b) 10
/ Division a = 5; b = 2; print(a / b) 2.5
% Modulus a = 5; b = 2; print(a % b) 1
** Exponentiation a = 5; b = 2; print(a ** b) 25
// Floor Division a = 5; b = 2; print(a // b) 2

In each example, the variable a is used to store the result of the operation, and then print(a) is used to display the output.

 

2. Comparison operators in Python

Comparison operators are also known as rational operators as well. They are used to compare different values.  They evaluate different types of expressions and manipulate the values of variables by performing different operations on them.

Operator Description Python Code Example Output
== Checks if the values on either side of the operator are equal, and returns True if they are. a = (5 == 3); print(a) False
!= Checks if the values on either side of the operator are not equal, and returns True if they aren't. a = (5 != 3); print(a) True
> Checks if the left-hand operand is greater than the right-hand operand, and returns True if it is. a = (9 > 4); print(a) True
< Checks if the left-hand operand is less than the right-hand operand, and returns True if it is. a = (3 < 7); print(a) True
>= Checks if the left-hand operand is greater than or equal to the right-hand operand. a = (7 >= 7); print(a) True
<= Checks if the left-hand operand is less than or equal to the right-hand operand. a = (4 <= 5); print(a) True

In each code example, the variable a is used to store the result of the comparison operation, and then print(a) is used to display the Boolean output (True or False).

 

3. Logical operators in Python

Python logical operators are used to evaluate the one or more than one condition between variables or operands by providing specific results. i.e True and False. Useful for making decisions in code (conditionals) and testing multiple conditions. It can be used with any data types that can be converted to Boolean values.

Operator Description Python Code Example Output
and Evaluates to True if both the left-hand and right-hand expressions are true. Otherwise, returns False. a = (True and True); print(a) True
or Evaluates to True if at least one of the left-hand or right-hand expressions is true. Otherwise, returns False. a = (True or False); print(a) True
not Reverses the Boolean value of the expression it precedes. If the expression is True, not makes it False. a = not True; print(a) False

In each example, the variable a is used to store the result of the logical operation, and print(a) is used to display the resulting Boolean value (True or False).

 

4. Assignment Operators

Assignment operators are primarily used to assign values to variables. They perform a single function of assigning a value from the right-hand side to the variable on the left-hand side. It is useful for initializing variables and updating their values.

Below is a table that explains the assignment operators in Python, along with code examples using a small variable name (a) and the print() statement to display the result.

Operator Description Python Code Example Output
= Assigns the value on the right to the variable on the left. a = 5; print(a) 5
+= Adds the right-hand operand to the left-hand operand and assigns the result to the left-hand operand. a = 5; a += 3; print(a) 8
-= Subtracts the right-hand operand from the left-hand operand and assigns the result to the left-hand operand. a = 9; a -= 4; print(a) 5
*= Multiplies the right-hand operand by the left-hand operand and assigns the result to the left-hand operand. a = 6; a *= 7; print(a) 42
/= Divides the left-hand operand by the right-hand operand and assigns the result to the left-hand operand. a = 8; a /= 2; print(a) 4.0
%= Takes the modulus of the left-hand operand by the right-hand operand and assigns the result to the left-hand operand. a = 10; a %= 3; print(a) 1
**= Raises the left-hand operand to the power of the right-hand operand and assigns the result to the left-hand operand. a = 2; a **= 3; print(a) 8
//= Performs floor division on the left-hand operand by the right-hand operand and assigns the result to the left-hand operand. a = 7; a //= 3; print(a) 2

In each example, the variable a is initially assigned a value. Then, an assignment operator modifies this value, and print(a) displays the updated value.

 

5. Augmented Operators (Compound Assignment Operators)

Python has a set of operators known as "augmented assignment operators," also sometimes called "compound assignment operators." These operators provide a shorthand way to apply an operation and an assignment in a single step. They are similar to assignment operators but perform an additional operation before the assignment.

Unlike normal assignment operators, Augmented Assignment Operators are used to replace those statements where a binary operator takes two operands, variable1 and variable1 and then assigns a final result back to one of the operands.

Below is a table that outlines the augmented assignment operators in Python, complete with code examples using a small variable name (a) and the print() function to display the result.

Operator Description Python Code Example Output
+= Adds the right-hand operand to the left-hand operand and assigns the result to the left-hand operand. a = 5; a += 2; print(a) 7
-= Subtracts the right-hand operand from the left-hand operand and assigns the result to the left-hand operand. a = 10; a -= 3; print(a) 7
*= Multiplies the right-hand operand by the left-hand operand and assigns the result to the left-hand operand. a = 4; a *= 3; print(a) 12
/= Divides the left-hand operand by the right-hand operand and assigns the result to the left-hand operand. a = 8; a /= 2; print(a) 4.0
%= Takes the modulus of the left-hand operand by the right-hand operand and assigns the result to the left-hand operand. a = 10; a %= 3; print(a) 1
**= Raises the left-hand operand to the power of the right-hand operand and assigns the result to the left-hand operand. a = 2; a **= 3; print(a) 8
//= Performs floor division on the left-hand operand by the right-hand operand and assigns the result to the left-hand operand. a = 7; a //= 3; print(a) 2
&= Performs bitwise AND on both operands and assigns the result to the left-hand operand. a = 5; a &= 3; print(a) 1
|= Performs bitwise OR on both operands and assigns the result to the left-hand operand. a = 5; a |= 3; print(a) 7
^= Performs bitwise XOR on both operands and assigns the result to the left-hand operand. a = 5; a ^= 3; print(a) 6
<<= Left shifts the bits of the left-hand operand by the right-hand operand and assigns the result to the left-hand operand. a = 5; a <<= 1; print(a) 10
>>= Right shifts the bits of the left-hand operand by the right-hand operand and assigns the result to the left-hand operand. a = 5; a >>= 1; print(a) 2

In each example, the variable a is initially assigned a value. Then, an augmented assignment operator modifies this value, and print(a) displays the updated value.

 

6. Bitwise Operators

Bitwise operators in Python are used to operate at a binary level. This means they look directly at the binary digits or binary bits of an integer. Below is a table that explains each bitwise operator in Python, along with a code example that uses a small variable name (a) and the print() statement to display the result.

Operator Description Python Code Example Output
& Bitwise AND: Sets each bit to 1 if both bits are 1. a = 5 & 3; print(a) 1
` ` Bitwise OR: Sets each bit to 1 if one of two bits is 1. `a = 5
^ Bitwise XOR: Sets each bit to 1 if only one of two bits is 1. a = 5 ^ 3; print(a) 6
~ Bitwise NOT: Inverts all the bits. a = ~5; print(a) -6
<< Left Shift: Shifts the bits of the number to the left by the specified number of positions. a = 5 << 1; print(a) 10
>> Right Shift: Shifts the bits of the number to the right by the specified number of positions. a = 5 >> 1; print(a) 2

 

Below are some examples to help you understand how these operators work in Python:

Bitwise AND (&):This operator compares each binary digit of the first operand to the corresponding binary digit of the second operand. If both digits are 1, the digit in the resulting binary representation is 1, otherwise 0.

a = 5  # binary: 0101
b = 3  # binary: 0011

result = a & b  # binary: 0001 -> decimal: 1

print("Bitwise AND:", result)

Bitwise OR (|): This operator also compares each binary digit of the first operand to the corresponding binary digit of the second operand. If either of the digits is 1, the resulting binary digit is 1.

a = 5  # binary: 0101
b = 3  # binary: 0011

result = a | b  # binary: 0111 -> decimal: 7

print("Bitwise OR:", result)

Bitwise XOR (^): The XOR operator compares each bit of its first operand to the corresponding bit of its second operand. If one bit is 0 and the other bit is 1, the corresponding result bit is set to 1.

a = 5  # binary: 0101
b = 3  # binary: 0011

result = a ^ b  # binary: 0110 -> decimal: 6

print("Bitwise XOR:", result)

Bitwise NOT (~): This operator is a unary operator, meaning it works with a single operand. Bitwise NOT will invert the number's bit-wise representation. Note that because Python uses signed integers, the result will be the two's complement of the inverted bits.

a = 5   # binary: 0101

result = ~a  # binary: -0110 -> decimal: -6

print("Bitwise NOT:", result)

Left Shift (<<): The left shift operator shifts the bits of a number to the left by a specified number of positions. Each left shift doubles the number, as it is equivalent to multiplication by 2 to the power of the number of shifted positions.

a = 5  # binary: 0101

result = a << 1  # binary: 1010 -> decimal: 10

print("Left Shift:", result)

Right Shift (>>): The right shift operator shifts the bits of a number to the right by a specified number of positions. Each right shift halves the number, rounding down.

a = 5  # binary: 0101

result = a >> 1  # binary: 0010 -> decimal: 2

print("Right Shift:", result)

 

7. Identity Operators

Identity operators in Python are used to compare the memory locations of two objects. They help to check if two variables refer to the same object in memory. Below is a table that describes the identity operators, accompanied by Python code examples using small variable names (a and b) and the print() function to display the result.

Operator Description Python Code Example Output
is Evaluates to True if the variables on either side of the operator point to the same object. a = [1, 2, 3]; b = a; print(a is b) True
is not Evaluates to True if the variables on either side of the operator do not point to the same object. a = [1, 2, 3]; b = [1, 2, 3]; print(a is not b) True

 

Description and Use-cases

is Operator: The is operator checks whether both the operands refer to the same object (i.e., point to the same memory location). It's often used to test if a variable is None, although it can also be used for other objects like lists or dictionaries to ensure that two variables point to the same data structure.

a = None
print(a is None)  # Output will be True

is not Operator: The is not operator is essentially the opposite of the is operator. It checks whether two variables refer to different objects in memory. This is useful for ensuring that two variables don't share the same underlying data.

a = [1, 2, 3]
b = [1, 2, 3]
print(a is not b)  # Output will be True

Remember, is and is not operators should not be confused with == and != operators. The former compare the memory locations, whereas the latter compare the values.

 

8. Membership Operators

Membership operators are used to test whether a value is a member of a sequence such as a list, tuple, or string, or a collection like a dictionary. Below is a table explaining the membership operators in Python, with code examples using small variable names (a and b) and the print() statement to display the result.

Operator Description Python Code Example Output
in Checks if the specified element exists within the sequence or collection. a = [1, 2, 3]; print(2 in a) True
not in Checks if the specified element does not exist within the sequence or collection. b = "Hello"; print("z" not in b) True

 

Description and Use-cases

in Operator: The in operator is used to check if a value exists in a sequence or a collection. It's a quick way to check for the presence of a specific item.

# Using 'in' with a list
a = [1, 2, 3, 4, 5]
print(3 in a)  # Output will be True

# Using 'in' with a string
b = "Hello World"
print("World" in b)  # Output will be True

not in Operator: The not in operator is essentially the opposite of the in operator. It checks if a specified element is not present in a given sequence or collection.

# Using 'not in' with a list
a = [1, 2, 3, 4, 5]
print(6 not in a)  # Output will be True

# Using 'not in' with a string
b = "Hello World"
print("Python" not in b)  # Output will be True

 

Assignment Vs Augmented Assignment Operators

The fundamental difference between assignment operators and augmented assignment operators lies in their functionality and readability.

 

Assignment Operators:

Basic Function: Assignment operators are mainly used to assign values to variables.

a = 5
b = 10

Single Operation: Assignment operators perform just one function: they assign the value on the right-hand side to the variable on the left-hand side.

a = b  # 'a' now holds the value that 'b' holds, which is 10.

Multiple Steps for Operations: If you need to perform an operation (like addition, subtraction, etc.) and then assign the result to the variable, you have to do it in multiple steps or lines.

a = a + 2  # Increment 'a' by 2.

 

Augmented Assignment Operators:

Enhanced Function: Augmented assignment operators perform an operation in addition to assignment, effectively combining the two into a single action.

a += 2  # This is equivalent to a = a + 2

Conciseness: They allow for more concise code. Instead of writing a = a + 2, you can simply write a += 2.

Efficiency: Augmented assignment operators may be more efficient in some cases, as they can reduce the amount of typing and potentially perform the operation faster, although the speed difference is generally negligible for basic types.

Multiple Operations: They make it easier to perform complex calculations and reassignments in a single step.

a *= 3  # This is equivalent to a = a * 3

 

Operators precedence order in Python

Operator precedence in Python determines the order in which operators are evaluated when multiple operators are present in an expression. Operators with higher precedence are evaluated before operators with lower precedence.

Here is a list of operators in Python, sorted from highest precedence to lowest:

  1. Parentheses (): Expressions inside parentheses are evaluated first.
  2. Exponentiation **: Right-to-left associativity.
  3. Complement, Unary Plus and Minus ~ + -: Unary operators.
  4. Multiply, Divide, Floor Divide, and Modulus * / // %: Left-to-right associativity.
  5. Addition and Subtraction + -: Left-to-right associativity.
  6. Bitwise Right Shift and Left Shift >> <<: Left-to-right associativity.
  7. Bitwise AND &: Left-to-right associativity.
  8. Bitwise XOR ^: Left-to-right associativity.
  9. Bitwise OR |: Left-to-right associativity.
  10. Comparison Operators == != < <= > >=: Left-to-right associativity.
  11. Identity Operators is is not: Left-to-right associativity.
  12. Membership Operators in not in: Left-to-right associativity.
  13. Logical NOT not: Right-to-left associativity.
  14. Logical AND and: Left-to-right associativity.
  15. Logical OR or: Left-to-right associativity.
  16. Conditional Expression if else: Right-to-left associativity.
  17. Assignment =: Right-to-left associativity.
  18. Augmented Assignment += -= *= /= //= %= **= &= ^= |= <<= >>=: Right-to-left associativity.

 

When multiple operators have the same precedence, Python usually evaluates them from left to right (left-to-right associativity). The exception to this rule is the exponentiation operator (**), which has right-to-left associativity, meaning that operations are evaluated from right to left.

For example:

  • With the expression 3 + 4 * 2, the multiplication (*) operator has higher precedence than addition (+), so 4 * 2 is evaluated first, resulting in 3 + 8 which is 11.
  • In the expression 2 ** 3 ** 2, the ** operator is right associative, so 3 ** 2 is evaluated first, resulting in 2 ** 9 which is 512

 

Special Cases and Syntax

Python allows some operators to be used in unconventional ways. For example, you can use the * operator to repeat strings and lists.

print("A" * 5)  # Output: AAAAA
print([1, 2] * 2)  # Output: [1, 2, 1, 2]

While using operators, you should follow certain syntax rules, like putting them between operands (in infix notation), or ensuring that they are applied to compatible data types.

 

Chaining: Python allows you to chain multiple comparisons to perform a more complex test.

a = 5
print(2 < a < 10)  # Output: True

Chained comparisons also benefit from short-circuit behavior. This means that if one comparison fails, the remaining ones are not executed, which can improve performance.

 

Mixing Operators in Expressions: Python allows for mixing certain types of operators, but it's important to use parentheses to make the expression clear.

print(3 + 4 * 2 / (1 - 5))  # Output: 1.0

When mixing operators with different data types, Python will usually automatically convert the types to make them compatible, if possible.

print(3 + 4.0)  # Output: 7.0

 

Common Mistakes and Best Practices

Importance of Parentheses

Clarifying Ambiguity: Parentheses help in making the expression unambiguous. This is especially crucial when dealing with operators of different precedences.

# Avoid
print(3 + 4 * 2 - 1)  # Output: 10

# Best Practice
print((3 + 4) * (2 - 1))  # Output: 7

Parentheses can also make complex expressions more readable, even if they're not strictly necessary.

 

Floating-Point Arithmetic Caveats

Precision: Floating-point numbers do not always represent decimal numbers precisely, which can lead to errors in calculations.

# Avoid
print(0.1 + 0.2 == 0.3)  # Output: False

# Best Practice
print(abs(0.1 + 0.2 - 0.3) < 1e-9)  # Output: True

Integer Division: When dividing integers, use // for integer division and / for floating-point division to avoid unexpected results.

# Avoid
print(5 / 2)  # Output: 2.5

# Best Practice
print(5 // 2)  # Output: 2

 

Common Pitfalls with Assignment Operators

Immutable Reassignment: Be cautious when you are working with immutable types like tuples or strings. Reassignment will produce a new object instead of modifying the original one.

# Ineffective
a = "Hello"
a[0] = "h"  # Raises TypeError

# Effective
a = "hello"

Augmented Assignment: Remember that augmented assignment (+=, *= etc.) can behave differently for mutable and immutable objects.

# Mutable
a = [1, 2, 3]
b = a
a += [4, 5]
print(b)  # Output: [1, 2, 3, 4, 5]

# Immutable
a = 5
b = a
a += 2
print(b)  # Output: 5

Chaining Assignments: While Python allows for chained assignments like a = b = 1, be cautious when using this feature with mutable objects as it can lead to unexpected behavior.

# Risky
a = b = []
a.append(5)
print(b)  # Output: [5]

 

Practical Examples

How to use Arithmetic Operators in Math Calculations

Arithmetic operators come in handy for a wide range of math calculations. Here we are calculating Area and Perimeter:

# Calculate the area of a circle
radius = 5
area = 3.14159 * radius ** 2
print("Area:", area)

# Calculate the perimeter of a rectangle
length, width = 10, 5
perimeter = 2 * (length + width)
print("Perimeter:", perimeter)

 

Using Comparison Operators in Conditional Statements

Comparison operators are frequently used in conditional statements like if, elif, and else. Here we are determining the Largest Number:

a, b, c = 5, 15, 10

if a > b and a > c:
    print("a is the largest.")
elif b > a and b > c:
    print("b is the largest.")
else:
    print("c is the largest.")

 

Using Logical Operators in Decision Making

Logical operators can be used for making complex decisions. Here we are checking the eligibility for a Loan:

income = 50000
credit_score = 700
if income > 40000 and credit_score > 600:
    print("Loan approved.")
else:
    print("Loan denied.")

 

Real-world Scenarios where Bitwise Operators are Useful

Bitwise operators are particularly useful in low-level programming and bit manipulation:

Setting Flags

# Suppose 0b0100 represents a read flag and 0b0010 represents a write flag.
flags = 0b0100 | 0b0010  # Setting both read and write flags

Checking Flags

# Check if the write flag is set
if flags & 0b0010:
    print("Write flag is set.")

 

How Membership and Identity Operators Work in Data Structures like Lists, Sets, and Dictionaries

Membership and identity operators are quite useful when working with data structures:

Lists

items = [1, 2, 3, 4]
if 2 in items:
    print("Found in list.")

Sets

unique_items = {1, 2, 3, 4}
if 3 in unique_items:
    print("Found in set.")

Dictionaries

student_data = {'name': 'Alice', 'grade': 'A'}
if 'name' in student_data:
    print("Name is present.")

 

Summary

Python has seven different types of operators. Arithmetic operators, logic operators, assignment operators, augmented operators, bitwise operators, and two special kinds of operators; membership operator and identity operator. In this tutorial, we learned about each type of these operators by taking different examples.  Moreover, we also covered the precedence of these operators over each other.

 

Further Reading

Python operators
Augmented operators
More about python operators

 

Bashir Alam

Bashir Alam

He is a Computer Science graduate from the University of Central Asia, currently employed as a full-time Machine Learning Engineer at uExel. His expertise lies in Python, Java, Machine Learning, OCR, text extraction, data preprocessing, and predictive models. You can connect with him on his LinkedIn profile.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment