Python operators are special symbols that perform operations on values and variables. Mastering each operator type is essential for writing efficient, readable, and idiomatic code. Whether you are a beginner or an experienced developer, this comprehensive guide covers all Python operators with practical examples and best practices.
In this article, you will learn about arithmetic, comparison, logical, assignment, bitwise, membership, and identity operators. We will explore each category in depth with code snippets you can run in your own environment.
If you are not yet familiar with Python variables and data types, we recommend checking out our complete guide on Python variables and data types before proceeding.
What Are Python Operators?
Operators are fundamental building blocks in any programming language. They let you manipulate data, make decisions, and control program flow. Python organizes its operators into seven main categories, each with a specific purpose. According to the official Python documentation, understanding operators correctly is one of the pillars of becoming a proficient Python programmer.
Let us dive into each category, starting with the simplest and moving toward the more advanced ones.
Arithmetic Operators
Arithmetic operators perform basic mathematical operations. They are the first operators every programmer learns and appear in virtually every program.
| Operator | Name | Example | Result |
|---|---|---|---|
+ | Addition | 5 + 3 | 8 |
- | Subtraction | 5 - 3 | 2 |
* | Multiplication | 5 * 3 | 15 |
/ | Division | 5 / 3 | 1.666... |
// | Floor Division | 5 // 3 | 1 |
% | Modulus | 5 % 3 | 2 |
** | Exponentiation | 5 ** 3 | 125 |
An interesting Python feature is that the + operator also concatenates strings, and * can repeat sequences. This behavior is called operator overloading and is one of the features that makes Python so expressive.
Practical Examples with Arithmetic Operators
# Basic operations
addition = 10 + 5 # 15
subtraction = 10 - 5 # 5
multiplication = 10 * 5 # 50
division = 10 / 3 # 3.3333333333333335
floor_division = 10 // 3 # 3
remainder = 10 % 3 # 1
exponentiation = 2 ** 10 # 1024
# String concatenation with +
name = "Python" + " " + "3.12"
print(name) # Python 3.12
# Repetition with *
line = "-" * 40
print(line) # ----------------------------------------
The modulus operator (%) is extremely useful for checking even or odd numbers, working with cycles, and implementing rotation logic. Floor division (//) is frequently used in binary search algorithms and index manipulation.
Comparison Operators
Comparison operators compare two values and return a boolean (True or False). They are the backbone of conditional structures and loops. Python supports all standard comparison operators and also offers chained comparisons, a feature few languages provide.
| Operator | Name | Example |
|---|---|---|
== | Equal to | 5 == 5 → True |
!= | Not equal | 5 != 3 → True |
> | Greater than | 5 > 3 → True |
< | Less than | 5 < 3 → False |
>= | Greater or equal | 5 >= 5 → True |
<= | Less or equal | 5 <= 3 → False |
Chained Comparisons
One of Python's most elegant features is the ability to chain comparisons. In many languages, you would write x > 5 and x < 10. In Python, you can simply write 5 < x < 10. This makes code more readable and natural, as highlighted in PEP 8 — the official Python style guide.
age = 25
# Chained comparison (Pythonic style)
if 18 <= age < 60:
print("Working-age adult")
# Equivalent in other languages
if age >= 18 and age < 60:
print("Working-age adult")
Chained comparisons work with any comparison operator and can have as many terms as needed. The interpreter evaluates each comparison individually and returns True only if all are true.
Logical Operators
Logical operators combine boolean expressions and are fundamental for flow control. Python uses the keywords and, or, and not, unlike languages such as C or JavaScript which use symbols like && and ||.
| Operator | Description | Example |
|---|---|---|
and | Returns True if both are True | True and False → False |
or | Returns True if at least one is True | True or False → True |
not | Inverts the boolean value | not True → False |
Short-Circuit Evaluation
Python uses short-circuit evaluation for logical operators. This means the expression is evaluated left to right and stops as soon as the result is determined. The Real Python tutorial on operators explains this concept in detail.
# Short-circuit with and: if the first condition is False,
# the second one is never evaluated
def safe_divide(a, b):
return b != 0 and a / b # Safe: no division by zero
print(safe_divide(10, 2)) # 5.0
print(safe_divide(10, 0)) # False (no error!)
This behavior is especially useful for avoiding errors in complex conditional expressions, such as checking that an object is not null before accessing its attributes.
Assignment Operators
Assignment operators are used to assign values to variables. Beyond the basic = operator, Python offers compound assignment operators that combine assignment with another operation. The W3Schools Python operators reference provides a complete table of all available operators.
x = 10 # Simple assignment
x += 5 # x = x + 5 → 15
x -= 3 # x = x - 3 → 12
x *= 2 # x = x * 2 → 24
x /= 4 # x = x / 4 → 6.0
x //= 2 # x = x // 2 → 3.0
x %= 2 # x = x % 2 → 1.0
x **= 3 # x = x ** 3 → 1.0
# Assignment with bitwise operators
y = 5 # 0b0101
y &= 3 # y = y & 3 → 1 (0b0001)
y |= 2 # y = y | 2 → 3 (0b0011)
y ^= 1 # y = y ^ 1 → 2 (0b0010)
y <<= 1 # y = y << 1 → 4 (0b0100)
y >>= 1 # y = y >> 1 → 2 (0b0010)
Compound assignment operators make code more concise and idiomatic. They are widely used in loops, accumulators, and data transformations.
Bitwise Operators
Bitwise operators work directly on the bits of integer numbers. Although they are less commonly used in everyday programming, they are essential in areas such as cryptography, image processing, network protocols, and performance optimization.
| Operator | Name | Description |
|---|---|---|
& | Bitwise AND | Both bits must be 1 |
| | Bitwise OR | At least one bit is 1 |
^ | Bitwise XOR | Bits must differ |
~ | Bitwise NOT | Inverts all bits |
<< | Left shift | Shifts bits left |
>> | Right shift | Shifts bits right |
a = 0b1100 # 12 in decimal
b = 0b1010 # 10 in decimal
print(bin(a & b)) # 0b1000 (8) - AND
print(bin(a | b)) # 0b1110 (14) - OR
print(bin(a ^ b)) # 0b0110 (6) - XOR
print(bin(~a)) # -0b1101 (-13) - NOT
print(bin(a << 1)) # 0b11000 (24) - Left shift
print(bin(a >> 1)) # 0b0110 (6) - Right shift
The XOR operator (^) is particularly interesting because it can swap two variables without a temporary variable — a classic technique featured in GeeksforGeeks tutorials on bitwise operators.
Membership Operators
Membership operators (in and not in) test whether a value belongs to a sequence or collection. They are widely used with lists, tuples, strings, dictionaries, and sets. The Programiz documentation on Python operators demonstrates several usage examples for these operators.
# Membership in lists
fruits = ["apple", "banana", "orange"]
print("banana" in fruits) # True
print("grape" not in fruits) # True
# Membership in strings
text = "Python is amazing"
print("Python" in text) # True
print("Java" in text) # False
# Membership in dictionaries (checks keys)
user = {"name": "John", "age": 30}
print("name" in user) # True
print("email" not in user) # True
Membership operators make code much more readable than manually iterating through a list with a for loop to check for an element's existence.
Identity Operators
Identity operators (is and is not) check whether two variables reference the same object in memory. It is important not to confuse is with ==: while == compares values, is compares object identity.
a = [1, 2, 3]
b = [1, 2, 3]
c = a
print(a == b) # True (same value)
print(a is b) # False (different objects)
print(a is c) # True (same object)
# Classic case: None
x = None
print(x is None) # True (correct way)
print(x == None) # True (works but not idiomatic)
The official Python documentation on expressions recommends using is to compare with None, True, and False. Using == for these comparisons works in practice but is not considered idiomatic.
Operator Precedence
Operator precedence determines the order in which operations are evaluated in an expression. Python follows a well-defined hierarchy, documented in the operator precedence section of the official documentation.
From highest to lowest precedence:
- Exponentiation (
**) - Bitwise complement (
~) and unary operators (+x,-x) - Multiplication, division, modulus (
*,/,//,%) - Addition and subtraction (
+,-) - Bitwise shifts (
<<,>>) - Comparison (
==,!=,>,<,>=,<=,is,in) - Bitwise AND (
&) - Bitwise XOR (
^) - Bitwise OR (
|) - Logical (
and,or,not) - Assignment (
=,+=, etc.)
# Complex precedence example
result = 2 + 3 * 4 ** 2
# Step by step:
# 1. 4 ** 2 → 16
# 2. 3 * 16 → 48
# 3. 2 + 48 → 50
print(result) # 50
# Use parentheses to be explicit
clear_result = 2 + (3 * (4 ** 2))
print(clear_result) # 50
The golden rule of precedence is: when in doubt, use parentheses. Parentheses not only guarantee the correct evaluation order but also make your code more readable for other developers. PEP 8 recommends using parentheses to group complex expressions.
Best Practices with Operators
Mastering operators goes beyond knowing the syntax. Here are some best practices endorsed by the Python community:
Write Idiomatic Code
Leverage Python's unique features in your code:
# ✅ Pythonic
if 0 < x < 10:
print("x is between 0 and 10")
# ❌ Avoid (other language style)
if x > 0 and x < 10:
print("x is between 0 and 10")
Prefer is None over == None
Although both work, is None is the convention adopted by the Python community and is slightly faster.
Beware of Floating Point
Never use == to compare floating point numbers. Due to how floats are represented in binary, direct comparisons can fail. Use math.isclose() for safe comparisons, as explained in the official tutorial on floating point errors.
import math
# ❌ Dangerous
if 0.1 + 0.2 == 0.3: # False!
print("Equal")
# ✅ Correct
if math.isclose(0.1 + 0.2, 0.3):
print("Approximately equal")
Explore Operator Overloading
Python lets you define how your own objects respond to operators through special methods (like __add__, __eq__, and so on). This is part of what makes libraries like NumPy and Pandas so powerful. To dive deeper into this topic, see the Python data model in the official documentation.
Practical Example: Operator Calculator
Let us consolidate everything we have learned with a practical example that uses multiple operator types:
def smart_calculator(a, b, operation):
"""Calculator supporting multiple operations."""
operations = {
"add": a + b,
"subtract": a - b,
"multiply": a * b,
"divide": a / b if b != 0 else "Error: division by zero",
"power": a ** b,
"modulo": a % b if b != 0 else "Error: modulo by zero",
}
return operations.get(operation, "Invalid operation")
# Testing
print(smart_calculator(10, 3, "add")) # 13
print(smart_calculator(10, 3, "divide")) # 3.333...
print(smart_calculator(10, 0, "divide")) # Error
print(smart_calculator(2, 8, "power")) # 256
This example combines arithmetic operators, comparison operators (to check for division by zero), membership operators (to look up in the dictionary), and the ternary conditional structure. To better understand how to create functions like this one, check out our complete guide to Python functions.
Conclusion
Operators are the backbone of any Python program. In this guide, we covered all seven categories of Python operators: arithmetic, comparison, logical, assignment, bitwise, membership, and identity.
To continue your studies, we recommend practicing with exercises on platforms like HackerRank Python, which offers challenges specific to each operator type. The more you practice, the more natural operators will become in your everyday code.
Remember: writing Pythonic code is not just about making code work, but about making it work elegantly, readably, and efficiently. Mastering operators is a fundamental step on that journey.