For working professionals
For fresh graduates
More
13. Print In Python
15. Python for Loop
19. Break in Python
23. Float in Python
25. List in Python
27. Tuples in Python
29. Set in Python
53. Python Modules
57. Python Packages
59. Class in Python
61. Object in Python
73. JSON Python
79. Python Threading
84. Map in Python
85. Filter in Python
86. Eval in Python
96. Sort in Python
101. Datetime Python
103. 2D Array in Python
104. Abs in Python
105. Advantages of Python
107. Append in Python
110. Assert in Python
113. Bool in Python
115. chr in Python
118. Count in python
119. Counter in Python
121. Datetime in Python
122. Extend in Python
123. F-string in Python
125. Format in Python
131. Index in Python
132. Interface in Python
134. Isalpha in Python
136. Iterator in Python
137. Join in Python
140. Literals in Python
141. Matplotlib
144. Modulus in Python
147. OpenCV Python
149. ord in Python
150. Palindrome in Python
151. Pass in Python
156. Python Arrays
158. Python Frameworks
160. Python IDE
164. Python PIP
165. Python Seaborn
166. Python Slicing
168. Queue in Python
169. Replace in Python
173. Stack in Python
174. scikit-learn
175. Selenium with Python
176. Self in Python
177. Sleep in Python
179. Split in Python
184. Strip in Python
185. Subprocess in Python
186. Substring in Python
195. What is Pygame
197. XOR in Python
198. Yield in Python
199. Zip in Python
If you've ever written even a single line of code in Python, chances are you've already used python operators without even realizing it. Whether you're adding two numbers, comparing values, or checking conditions, python operators are always at work behind the scenes. They're the building blocks of decision-making and calculations in any Python program.
In this blog, we're going to walk you through everything you need to know about python operators, from the basic arithmetic ones to the slightly trickier bitwise and identity operators. Whether you're a beginner trying to understand how things work or an intermediate coder brushing up your skills, this guide is your one-stop solution. However, before we start, you should brush up your Python data types learning.
And to make it even easier, each code snippet comes with comments, expected output, and a brief explanation. Learning code here, will assuredly help you easily understand any of the top-rated software development course.
Before we get into the different types, let's first understand what python operators really are.
Python operators are special symbols or keywords that perform operations on variables and values. In everyday Python programming, you’ll use these operators to do things like:
Think of python operators as tools in your coding toolbox—they help you build logic and manipulate data efficiently. Just like a calculator has buttons for `+`, `-`, `*`, and `/`, Python has its own set of operators to make coding intuitive and powerful.
Fast-pace your career growth with the following full-stack development courses:
Here's a simple example:
#Calculating her total marks
maths = 85
science = 90
# Using the + operator to find the total
total_marks = maths + science
print("Total Marks:", total_marks)
Output:
Total Marks: 175
Explanation:
In this example, the `+` sign is an arithmetic operator. It takes two variables—`maths` and `science`—and adds their values. Simple, right?
Throughout this blog, we’ll explore each category of python operators in detail, backed by practical code examples. Additionally, numerous developers get confused between operators and variables. To cut that clutter out, you should explore our articles about variables in Python.
Python offers a variety of operators, each designed to perform a specific kind of operation. To make things easier to understand, we've broken them down into the following major types:
Each of these types plays a crucial role in writing efficient, readable, and logical Python code.
Also explore our detailed tutorial about Global Variable in Python!
Quick Overview Table:
Operator Type | Example Symbols | Use Case Example |
Arithmetic | +, -, *, / | marks + bonus |
Comparison | ==, !=, <, > | age >= 18 |
Logical | and, or, not | is_student and is_adult |
Bitwise | &, ` | , ^, ~` |
Assignment | =, +=, -= | x += 5 |
Identity | is, is not | a is b |
Membership | in, not in | 'a' in 'Rahul' |
Each of these python operators will be covered in detail in the upcoming sections with practical examples.
Arithmetic operations are some of the most common tasks in any programming language, and Python makes it easy with its intuitive arithmetic python operators. These operators are used to perform basic mathematical operations like addition, subtraction, multiplication, and more.
Here’s a list of the main arithmetic python operators:
Operator | Symbol | Description | Example |
Addition | + | Adds two operands | a + b |
Subtraction | - | Subtracts second from first | a - b |
Multiplication | * | Multiplies operands | a * b |
Division | / | Divides first by second | a / b |
Modulus | % | Remainder of division | a % b |
Exponentiation | ** | Raises first to the power of second | a ** b |
Floor Division | // | Division with result rounded down | a // b |
Let’s walk through each of these with examples.
# Exam scores in two subjects
maths = 88
english = 92
# Addition: Total score
total = maths + english # 88 + 92 = 180
# Subtraction: Score difference
difference = english - maths # 92 - 88 = 4
# Multiplication: Hypothetical scaling
scaled_score = maths * 2 # 88 * 2 = 176
# Division: Average score
average = total / 2 # 180 / 2 = 90.0
# Modulus: Remainder when total is divided by 7
remainder = total % 7 # 180 % 7 = 5
# Exponentiation: Square of maths score
square = maths ** 2 # 88 ** 2 = 7744
# Floor Division: Rounded down average
floor_div = total // 2 # 180 // 2 = 90
# Displaying all results
print("Total:", total)
print("Difference:", difference)
print("Scaled Score:", scaled_score)
print("Average:", average)
print("Remainder:", remainder)
print("Square of Maths:", square)
print("Floor Division of Total:", floor_div)
Output:
Total: 180
Difference: 4
Scaled Score: 176
Average: 90.0
Remainder: 5
Square of Maths: 7744
Floor Division of Total: 90
Explanation:
In this example, we used various arithmetic python operators to perform calculations based on Rahul’s marks. From basic addition and subtraction to more advanced operations like exponentiation and floor division, these operators help manage numeric data with ease.
Whether you're developing a billing system, analyzing scores, or doing data science, understanding these python operators is essential. Once you understand these operators, you’ll be a step-forward to leverage all advantages of Python programming.
Comparison operators, also known as relational operators, are used to compare two values or variables. These python operators return a Boolean value—either True or False—based on whether the comparison condition is met.
Comparison operators are critical in control flow (like if, while, and for statements) because they help the program make decisions.
List of Comparison Python Operators
Operator | Symbol | Description | Example |
Equal to | == | Checks if values are equal | a == b |
Not equal to | != | Checks if values are not equal | a != b |
Greater than | > | Checks if left is greater | a > b |
Less than | < | Checks if left is smaller | a < b |
Greater than or equal to | >= | Checks if left is greater or equal | a >= b |
Less than or equal to | <= | Checks if left is smaller or equal | a <= b |
Explore our article on Inheritance in Python to develop advanced-level programs.
# Rajat's age and minimum required age for college
rajat_age = 19
required_age = 18
# Using comparison operators to check conditions
is_eligible = rajat_age >= required_age # True
is_minor = rajat_age < 18 # False
exact_match = rajat_age == required_age # False
not_equal = rajat_age != required_age # True
# Displaying results
print("Is Rajat eligible for admission?", is_eligible)
print("Is Rajat still a minor?", is_minor)
print("Is Rajat exactly the required age?", exact_match)
print("Is Rajat's age not equal to required?", not_equal)
Output:
Is Rajat eligible for admission? True
Is Rajat still a minor? False
Is Rajat exactly the required age? False
Is Rajat's age not equal to required? True
Explanation:
Here, we used several comparison python operators to check Rajat’s age against a required threshold. These comparisons form the basis for many decision-making scenarios, like eligibility checks, access control, and conditional logic in programs.
Whether you're building a login system or filtering data, understanding how python operators compare values is crucial.
Once you've started comparing values, the next logical step (pun intended) is combining those comparisons. That’s where logical python operators come in. These operators help you evaluate multiple conditions at once, returning True or False based on the overall logic.
Logical operators are especially important in decision-making, form validations, and loops. By learning all these concepts, you’ll clear your path to become a Python developer with exceptional skills.
List of Logical Python Operators
Operator | Keyword | Description | Example |
AND | and | Returns True if both conditions are true | a > 10 and b < 20 |
OR | or | Returns True if at least one is true | a > 10 or b < 20 |
NOT | not | Reverses the result: True becomes False | not(a > 10) |
# Shradha's details
age = 18
marks = 75
# Admission criteria: must be at least 18 and have 70+ marks
is_age_eligible = age >= 18
has_good_marks = marks >= 70
# Using logical operators to evaluate overall eligibility
eligible_for_admission = is_age_eligible and has_good_marks # True
either_condition = is_age_eligible or has_good_marks # True
not_eligible = not eligible_for_admission # False
# Displaying the logical evaluations
print("Is Shradha eligible for admission?", eligible_for_admission)
print("Is she eligible based on either age or marks?", either_condition)
print("Is she not eligible?", not_eligible)
Output:
Is Shradha eligible for admission? True
Is she eligible based on either age or marks? True
Is she not eligible? False
Explanation:
In this example, we used all three logical python operators: and, or, and not. This allowed us to build more complex logic from simple comparison statements. These operators are essential when working with multiple criteria in any decision-making code.
As you continue building Python applications, you'll frequently combine comparison python operators with logical python operators to handle real-world scenarios effectively.
Do explore Memory Management in Python to build efficient programs.
Bitwise operations are a bit more advanced, but extremely powerful when you’re working at a lower level of data processing—like cryptography, image processing, or network programming. Bitwise python operators work directly with binary digits (bits) of integers.
Instead of evaluating whole numbers or logic, these python operators compare bits using binary logic.
List of Bitwise Python Operators
Operator | Symbol | Description | Example |
AND | & | Sets each bit to 1 if both bits are 1 | a & b |
OR | ` | ` | Sets each bit to 1 if one of two is 1 |
XOR | ^ | Sets each bit to 1 if only one is 1 | a ^ b |
NOT | ~ | Inverts all the bits | ~a |
Left Shift | << | Shifts bits left (adds zeros to right) | a << 1 |
Right Shift | >> | Shifts bits right (removes rightmost bits) | a >> 1 |
# Rajan's binary ID and age values
id_number = 10 # In binary: 1010
age = 4 # In binary: 0100
# Bitwise AND
bitwise_and = id_number & age # 1010 & 0100 = 0000
# Bitwise OR
bitwise_or = id_number | age # 1010 | 0100 = 1110
# Bitwise XOR
bitwise_xor = id_number ^ age # 1010 ^ 0100 = 1110
# Bitwise NOT
bitwise_not = ~id_number # ~1010 = -1011 (2's complement in Python)
# Left Shift
left_shift = id_number << 1 # 1010 becomes 10100 = 20
# Right Shift
right_shift = id_number >> 1 # 1010 becomes 0101 = 5
# Display results
print("Bitwise AND:", bitwise_and)
print("Bitwise OR:", bitwise_or)
print("Bitwise XOR:", bitwise_xor)
print("Bitwise NOT:", bitwise_not)
print("Left Shift:", left_shift)
print("Right Shift:", right_shift)
Output:
Bitwise AND: 0
Bitwise OR: 14
Bitwise XOR: 14
Bitwise NOT: -11
Left Shift: 20
Right Shift: 5
Explanation:
Bitwise operations can seem intimidating at first, but they become powerful tools once you understand them. Here, Rajan's id_number and age were used in several bitwise python operators to perform binary-level operations. These are rarely used in simple applications but are indispensable in technical fields where performance and memory optimization matter.
Remember: These python operators only work on integers and their binary representations.
Do explore Frameworks in Python to add next-gen functionalities in your applications.
Assignment operators in Python do more than just assign values to variables. They also provide shorthand notations to perform operations and assignments in a single line. This makes your code cleaner and more concise.
These assignment python operators are incredibly useful when updating the value of a variable based on its current value.
List of Assignment Python Operators
Operator | Description | Example |
= | Assigns value | a = 5 |
+= | Adds and assigns | a += 5 (same as a = a + 5) |
-= | Subtracts and assigns | a -= 3 |
*= | Multiplies and assigns | a *= 2 |
/= | Divides and assigns | a /= 4 |
%= | Modulus and assigns | a %= 2 |
**= | Exponentiation and assigns | a **= 2 |
//= | Floor division and assigns | a //= 3 |
&=, ` | =, ^=, >>=, <<=` | Bitwise updates |
# Initial balance
wallet = 1000
# Priya buys books
wallet -= 300 # wallet = wallet - 300
# She earns from tutoring
wallet += 500 # wallet = wallet + 500
# She invests part of it
wallet *= 1.1 # wallet = wallet * 1.1 (10% return)
# She donates a small amount
wallet /= 2 # wallet = wallet / 2
# Floor division to round off
wallet //= 1 # wallet = wallet // 1
print("Final wallet balance:", wallet)
Output:
Final wallet balance: 605.0
Explanation:
In this example, Priya starts with ₹1000 and goes through a series of transactions. Each step uses a different assignment python operator to update her balance. These operators simplify arithmetic expressions by combining them with assignment logic in a clean, readable way.
Once you're familiar with them, you'll find these python operators not only save time but also improve the clarity of your code.
Must read about Speech Recognition in Python to create AI-enabled applications.
While arithmetic, logical, and bitwise operations handle data, identity and membership operators help in working with objects and collections. These python operators are especially useful when dealing with lists, strings, or object references.
Let’s look at both types:
Identity operators are used to check whether two variables refer to the same object in memory—not just equal in value, but actually the same object.
Operator | Description | Example |
is | Returns True if both refer to same object | a is b |
is not | Returns True if they do not refer to same object | a is not b |
Example: Comparing Object Identity
# Two different lists with the same contents
list1 = [1, 2, 3]
list2 = [1, 2, 3]
list3 = list1 # list3 points to the same object as list1
# Identity checks
print("list1 is list2:", list1 is list2) # False
print("list1 == list2:", list1 == list2) # True (values are equal)
print("list1 is list3:", list1 is list3) # True
Output:
list1 is list2: False
list1 == list2: True
list1 is list3: True
Explanation:
list1 and list2 have the same values but are stored at different memory locations, so list1 is list2 is False. list3 is just another name for list1, so list1 is list3 is True. Identity python operators are commonly used when you need to ensure two references are pointing to the same object.
Do explore Merge Sort in Python to gain industry-level development knowledge.
Membership operators are used to check whether a value or variable is part of a sequence (like a list, tuple, string, or dictionary).
Operator | Description | Example |
in | Returns True if value exists | 'a' in 'Rajan' |
not in | Returns True if value does not exist | 'x' not in list |
Example: Checking Elements in Collections
# Rajan’s registered course list
courses = ['Python', 'Data Science', 'AI']
# Membership tests
print("Is 'Python' in Rajan's courses?", 'Python' in courses) # True
print("Is 'Java' not in Rajan's courses?", 'Java' not in courses) # True
# Checking character in string
name = "Rajan"
print("'a' in name:", 'a' in name) # True
print("'x' not in name:", 'x' not in name) # True
Output:
Is 'Python' in Rajan's courses? True
Is 'Java' not in Rajan's courses? True
'a' in name: True
'x' not in name: True
Explanation:
Membership python operators are incredibly handy for filtering, searching, and validating data in lists, strings, and other iterable types. They let you check if a value is present (or absent) without writing complex loops.
Together, identity and membership operators expand the utility of python operators, especially when working with objects and collections.
In Python, operator precedence determines the order in which operators are evaluated in an expression. Understanding this is crucial to ensure that your code produces the correct result.
Additionally, associativity defines the direction in which operators of the same precedence level are evaluated. By default, most operators have left-to-right associativity, but some operators, like exponentiation, evaluate right-to-left.
When you write an expression with multiple operators, Python follows a set of rules to decide which operator to apply first. The higher the precedence, the earlier the operator is applied.
Here’s a summary of the python operator precedence (from highest to lowest):
Operator Type | Operator | Precedence Order |
Parentheses | () | 1st |
Exponentiation | ** | 2nd |
Unary +, Unary - | +x, -x | 3rd |
Multiplication, Division, Modulus | *, /, %, // | 4th |
Addition, Subtraction | +, - | 5th |
Comparison Operators | ==, !=, <, >, <=, >= | 6th |
Logical AND | and | 7th |
Logical OR | or | 8th |
Assignment | =, +=, -= | 9th |
Example: Operator Precedence in Action
# Example using multiple operators
x = 5
y = 10
z = 2
result = x + y * z ** 2 # Exponentiation, multiplication, addition
# Order of operations:
# 1. z ** 2 = 2 ** 2 = 4
# 2. y * 4 = 10 * 4 = 40
# 3. x + 40 = 5 + 40 = 45
print("Result:", result) # Output will be 45
Output:
Result: 45
Explanation:
In this example, the exponentiation (z ** 2) is evaluated first because it has the highest precedence. Then, the multiplication (y * 4) is performed, followed by the addition (x + 40).
Most operators in Python follow left-to-right associativity, meaning they are evaluated from left to right. For example:
# Left-to-right evaluation
result = 5 - 3 + 2 # (5 - 3) + 2 = 4
However, exponentiation (**) is right-to-left associative. This means that expressions like 2 ** 3 ** 2 are evaluated from right to left, as 2 ** (3 ** 2):
# Right-to-left evaluation
result = 2 ** 3 ** 2 # 2 ** (3 ** 2) = 2 ** 9 = 512
Output:
Result: 512
Explanation:
In the case of exponentiation, 3 ** 2 is evaluated first, giving 9, and then 2 ** 9 is calculated, resulting in 512.
When in doubt about precedence, use parentheses () to make the order of operations explicit. Parentheses have the highest precedence in Python and ensure that the expression inside is evaluated first, overriding default precedence rules.
# Parentheses change the order of evaluation
result = (x + y) * z # (5 + 10) * 2 = 15 * 2 = 30
Output:
Result: 30
Explanation:
In this case, parentheses are used to force addition to happen before multiplication, giving a different result from the previous example.
In this blog, we have explored the different types of Python operators that are essential for performing various operations on data. From arithmetic and logical operations to comparison and bitwise manipulations, python operators form the foundation of decision-making and complex computations in Python programming.
Key Takeaways:
In Python, `=` is the assignment operator, used to assign values to variables. For example, `x = 10` assigns 10 to the variable `x`. On the other hand, `==` is the equality operator, used to compare two values. It returns `True` if the values are equal and `False` otherwise.
You can use the identity operator `is` to check if two variables point to the same object in memory. For example, `a is b` will return `True` if `a` and `b` refer to the same object, and `False` if they are different objects, even if they have the same value.
Common arithmetic operators in Python include `+` (addition), `-` (subtraction), `*` (multiplication), `/` (division), `//` (floor division), `%` (modulus), and `**` (exponentiation). These operators perform basic mathematical calculations on numbers, both integers and floats.
The `not` operator is a logical operator that reverses the boolean value of an expression. If the expression is `True`, `not` changes it to `False`, and vice versa. It’s commonly used in conditional statements to check for the negation of a condition, such as `if not x`.
Yes, you can combine multiple Python operators in a single expression, but operator precedence determines the order in which they are evaluated. Parentheses `()` can be used to override the default precedence and ensure that certain operations are performed first, making complex expressions clearer and more predictable.
In Python, `and` and `or` are logical operators used to combine multiple conditions. The `and` operator returns `True` only if both conditions are `True`, while `or` returns `True` if at least one condition is `True`. These operators are commonly used in `if` statements to check multiple conditions.
Bitwise operations in Python are performed using operators like `&` (AND), `|` (OR), `^` (XOR), `~` (NOT), `<<` (left shift), and `>>` (right shift). These operators work at the binary level and are typically used for tasks such as low-level data manipulation or optimization in specific use cases like cryptography.
Python assignment operators like `+=` are shorthand operators that combine an operation with assignment. For example, `x += 5` is equivalent to `x = x + 5`. These operators allow you to perform operations and update the variable in a more concise way, saving lines of code and improving readability.
In Python, `is not` is the negation of the `is` operator, used to check if two variables do not refer to the same object in memory. For example, `a is not b` returns `True` if `a` and `b` are different objects, even if they have the same value.
You can use the `in` operator to check if a value exists in a sequence like a list, tuple, or string. For example, `5 in [1, 2, 3, 4, 5]` returns `True`. To check if a value is not in a sequence, use the `not in` operator, such as `6 not in [1, 2, 3, 4, 5]`.
Python operators follow a specific order of precedence. For example, arithmetic operators like `*` and `/` have higher precedence than `+` and `-`, and comparison operators like `==` have lower precedence than arithmetic ones. Using parentheses can help override the default precedence and ensure the correct order of evaluation in complex expressions.
Take our Free Quiz on Python
Answer quick questions and assess your Python knowledge
Author|900 articles published
Previous
Next
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918068792934
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.