Types of operators in Python

Tutorial Playlist

To become an expert in Python programming and creating effective Python programs, you must know Python operators. Python has a variety of operators that allow one to perform simple arithmetic operations, complex logical tests, and many other operations in Python.

Every section in this tutorial on Python Operators has real-life examples and use cases for working with such operators, and through them, you will develop confidence in working with operators in Python in real programs and will have cleaner and more efficient codes.

Table of Contents:

What are Python Operators?

Python operators are the special type of symbols or keywords that generally perform different kinds of operations on variables and values. These operators typically act as instructions that Python interprets in order to perform operations like calculations, comparisons, and logical evaluations.

Operators in Python are one of the most important concepts in Python programming that allows developers to manipulate any data, perform mathematical calculations, and maintain the flow of programs effectively. Whether you are doing any arithmetic operations, making logical decisions, or even assigning values, these Python operators generally streamline code execution and improve performance in your Python development.

Types of Operators in Python

  • Arithmetic Operators: Useful in addition, subtraction, multiplication, and division operators.
  • Comparison (Relational) Operators: Useful to evaluate values and direct program flow.
  • Assignment Operators: Useful to assign and update variable values effectively.
  • Logical Operators: Form compound conditions in decision structures.
  • Membership and Identity Operators: Alter strings and differentiate references in memory.
  • Bitwise Operators: It work with direct binary representations of numbers.

Arithmetic Operators in Python

Arithmetic operators are used to perform various mathematical operations such as addition, subtraction, etc. The following table contains all the arithmetic operations and their descriptions, along with examples.

Operator Name Example Description
+ Addition 10 + 5 Adds two values
Subtraction 10 – 5 Subtracts the second value from the first
* Multiplication 10 * 5 Multiplies two values
/ Division 10 / 3 Divides the first value by the second
% Modulus 10 % 3 Returns the remainder of the division
** Exponentiation 2 ** 3 Raises the first value to the power of the second
// Floor Division 10 // 3 Returns the integer part of the division

Example: Arithmetic Operators in Python

Python

Output:

Arithmetic Operators in Python Output

Comparison Operators in Python

Comparison Operators also called relational operators generally compare the values on both sides of the operator and conclude on the relation between the values. After comparison, it returns the Boolean value, i.e., either true or false. The following table contains different types of comparison operators and their descriptions, along with respective examples.

Operator Name Example Description
== Equal to 5 == 5 Returns True if values are equal
!= Not equal to 5 != 3 Returns True if values are different
< Less than 3 < 5 Returns True if the first value is smaller
> Greater than 5 > 3 Returns True if the first value is larger
<= Less than or equal to 5 <= 5 Returns True if the first value is smaller or equal
>= Greater than or equal to 5 >= 3 Returns True if the first value is larger or equal

Example: Comparison Operators in Python

Python

Output:

Comparison Operators in Python Output

Assignment Operators in Python

Assignment operators are used to assign values to Python Variables. The assignment is sometimes done directly, and sometimes the operator first performs some kind of mathematical operation and then assigns the value to the operand. The following table contains all types of assignment operators with their descriptions and respective examples.

Operator Name Example Description
= Assignment x = 5 Assign 5 to x
+= Add and assign x += 3 Equivalent to x = x + 3
-= Subtract and assign x -= 2 Equivalent to x = x – 2
*= Multiply and assign x *= 4 Equivalent to x = x * 4
/= Divide and assign x /= 2 Equivalent to x = x / 2
%= Modulus and assign x %= 3 Equivalent to x = x % 3

Example: Assignment Operators in Python

Python

Output:

Assignment Operators in Python Output

Logical Operators in Python

Logical operators are mainly used for conditional statements. There are three types of logical operators, namely, AND, OR, and NOT. The following table contains all logical operators with their descriptions, as well as their respective examples.

Operator Name Example Description
and Logical AND True and False Returns True if both conditions are True
or Logical OR True or False Returns True if at least one condition is True
not Logical NOT not True Returns the opposite of the condition

Example: Logical Operators in Python

Python

Output:

Logical Operators in Python Output
Short-Circuit Evaluation in Logical Operators

The ‘and’ & ‘or’ operators in Python generally follow the short circuit evaluation which means that they simply stop checking the expressions as the result is being calculated.

Example:

Python

Output:

Short-Circuit Evaluation in Logical Operators Output

This behavior of Python logical operators typically improves the overall performance and also prevents unnecessary function calls.

Membership Operators in Python

Membership operators are used to test if a value is available in a sequence or not. It can be any sequence such as (Python String, Python List, Python Set, Python Tuple, and Python Dictionary). There are two types of membership operators, namely, in and not in. The following table contains the description and the respective examples of both membership operators.

Operator Name Example Description
in Membership 5 in [1, 2, 3, 4, 5] Returns True if the value is found in the sequence
not in Not Membership 5 not in [1, 2, 3, 4] Returns True if the value is not found in the

Example: Membership Operators in Python

Python

Output:

Membership Operators in Python Output

Bitwise Operator in Python

It performs bit-by-bit operations. For instance, suppose there are two variables,

 I = 10 and J = 20

Their binary values are:

I = 10 = 0000 1010

J = 20 = 0001 0100

Now, let us see how the bitwise operator in Python works.

Operator Name Example Description
& Binary AND 5 & 3 Performs AND on each bit
| Binary OR 5 | 3 Performs OR on each bit
^ Binary XOR 5 ^ 3 Performs XOR on each bit
~ Binary Complement ~5 Inverts all bits
<< Left Shift 5 << 1 Shifts bits left by 1
>> Right Shift 5 >> 1 Shifts bits right by 1

Example: Bitwise Operators in Python

Python

Output:

Bitwise Operators in Python Output

Identity Operators in Python

Identity operators are used to compare the memory addresses of two different objects. The two types of identity operators in Python are ‘is’ and ‘is not’. The following table contains the description of these two operators, along with their respective examples.

Operator Name Example Description
is Identity a is b Returns True if both variables point to the same object in memory
is not Not Identity a is not b Returns True if both variables do not point to the same object in memory

Example: Identity Operators in Python

Python

Output:

Identity Operators in Python Output

Ternary Operators in Python

Ternary operators, which can also be called conditional expressions evaluate something based on a particular condition being true or false. It simply allows the programmer to test a condition in a single line replacing the multi-line if-else statements, and hence makes the code compact. They are more concise than a traditional if…else statement.

Example: Ternary Operators in Python

Python

Output:
Ternary Operators in Python Output

Augmented Assignment Operators

The augmented assignment operators in Python are the combination of arithmetic operators and assignment operators that are used to improve the overall code efficiency.

Operator Equivalent Expression
+= a = a + b
-= a = a – b
*= a = a * b
/= a = a / b
//= a = a // b
%= a = a % b
**= a = a ** b

Example: Augmented Assignment Operators

Python

Output:

Augmented Assignment Operators output

Python Operator Precedence

In some expressions, there is more than one operator. To evaluate such expressions, there is a rule of precedence, known as Python Operator Precedence. It guides the order in which these operations are carried out.

The table in the image given below shows the operator precedence in Python in descending order:

Python Operator Precedence

Operator Overloading in Python

Operator Overloading lets you extend the meaning of operators that are predefined. It provides an expanded definition of the operator. The same operator also behaves in different ways with different data types. Take the example of the + operator. It performs addition when done on numbers, but will concatenate two strings and merge two lists.

Example:

Python

Output:

Output
When p1 + p2 is executed, the __add__ method is called, and the result is a new Point object with the sum of the x and y values.

Using the operator Module for Functional Programming

The operator module of Python mostly provides a group of optimized and built-in operators mostly equaling the regular operators. It typically has a very major contribution towards functional programming where the functions are mostly treated with importance and can be conducted in a more readable and concise way.

Python’s operator module works seamlessly with map(), filter(), and reduce() and merely makes the processes optimized and more efficient.

1. Using operator.add with map()

Python

Output:

Using operator.add with map()

Here, operator.mul replaces lambda x: x * 2, making the function call more efficient.

2. Using operator with reduce()

Python

Output:

Using operator with reduce() Output

Instead of using lambda a, b: a + b, operator.add makes the code cleaner and faster.

3. Sorting with operator.attrgetter()

Python

Output:

Sorting with operator.attrgetter() Output

Here, operator.attrgetter(“marks”) makes sorting based on object attributes more elegant.

Using the Walrus Operator (:=) for Performance Optimization

The Walrus operator (:=) of Python, implemented in the 3.8 version of Python, mostly offers the assignment within the expressions that simply boosts the performance of the code by not performing redundant calculations. It’s very useful in a lot of concepts of Python such as loops, list comprehensions, and conditional statements where every value is mostly needed more than once.

Example: Without Walrus Operator

Python

Output:

Without Walrus Operator

Here, value ** 2 is calculated twice (once in the if condition and again in append).

Example: With Walrus Operator

Python

Output:

Without Walrus Operator

  • It will boost the performance gain as the computation happens only once per iteration.
  • It also Improves readability by reducing redundant calculations.

How Python Handles Floating-Point Precision in Arithmetic Operators

Python generally uses IEEE 754 double-precision floating-point format that simply can lead to precision errors in arithmetic operations.

Python

Output:

Point Precision in Arithmetic Operators

Instead of 0.3, Python returns 0.30000000000000004 due to binary representation limitations.

How to Handle Floating-Point Precision Issues

  1. Using the decimal Module for High-precision
Python

Output:

Using the decimal Module for High-precision

  1. Using round() to Limit Precision
Python

Output:

Using round() to Limit Precision

  1. Using math.isclose() for Comparisons
Python

Output:

Using math.isclose() for Comparisons

Key Takeaways:

  • Python typically stores the float in binary which leads to rounding issues.
  • Use a decimal module when exact precision is required.
  • Use math.isclose() for reliable floating-point comparisons.

Conclusion

With that, you have completed this Python Operators Tutorial in detail, having acquired in-depth mastery in working with operators for efficient and well-organized Python development. Let’s go over some important points:

Key Takeaways for Python Developers:

  • Types of Python Operators: You understand Python arithmetic operators, Python relational operators, Python assignment operators, Python logical operators, Python membership operators, Python bitwise operators, and Python identity operators and when and why they’re utilized in real life.
  • Optimum Code Practices: Appropriate use of comparison and assignment operators can make a big impact on codes.
  • Hands-on Exercise: Practise examples have aided in creating a sound basis for effective working with operators for you.

Now, in case, you’re interested in knowing about practicing data science techniques with Python, then you can refer to this blog regarding Python Data Science tutorial.

Also, review our Python certification training Course. Besides, go through these free Python Interview Questions prepared by professionals in the field.

Operators in Python - FAQs
1. What are operators in Python?

Operators in Python refer to specific characters in Python that enable operations between values and variables.

2. What are the different types of operators in Python?

The operators in Python fall under various categories like arithmetic, comparison, logical, assignment, bitwise, membership, and identity operators.

3. What is operator precedence in Python?

Operator precedence in Python is a function of the order in which operators in an expression will be evaluated.

4. Can I extend the meaning of predefined operators in Python?

Yes, Python operators can be overloaded with a specific meaning using operator overloading.

5. What are some common use cases for Python operators in real-world applications?

Python operators have numerous applications in numerous industries including Data analysis and science, Machine Learning, web development, Automation, and Scientific computation

Our Python Courses Duration and Fees

Program Name
Start Date
Fees
Cohort starts on 11th Mar 2025
₹20,007

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.