dotlinux blog

The Ultimate Guide to Python Operators with Examples

Operators are the building blocks of any programming language, and Python is no exception. They allow you to perform operations on variables and values, enabling everything from simple arithmetic to complex logical checks. Whether you’re a beginner learning the ropes or an experienced developer brushing up on fundamentals, understanding Python operators is critical for writing clean, efficient, and bug-free code.

In this guide, we’ll explore every type of operator in Python with detailed explanations, practical examples, and common use cases. By the end, you’ll have a comprehensive understanding of how to leverage operators to solve real-world problems.

2026-03

Table of Contents#

  1. Arithmetic Operators
  2. Assignment Operators
  3. Comparison Operators
  4. Logical Operators
  5. Bitwise Operators
  6. Identity Operators
  7. Membership Operators
  8. Operator Precedence
  9. Advanced Topics
  10. Conclusion
  11. References

1. Arithmetic Operators#

Arithmetic operators perform basic mathematical operations. Python supports all standard arithmetic operations, plus a few unique ones like floor division and modulus.

OperatorNameDescriptionExampleOutput
+AdditionAdds two operands5 + 38
-SubtractionSubtracts the right operand from the left10 - 46
*MultiplicationMultiplies two operands6 * 742
/DivisionDivides the left operand by the right (returns float)15 / 43.75
//Floor DivisionDivides and returns the largest integer ≤ result15 // 43
%ModulusReturns the remainder of division15 % 43
**ExponentiationRaises the left operand to the power of the right2** 38

Key Examples:#

  • Division vs. Floor Division:
    Regular division (/) always returns a float, even if the result is an integer:

    print(10 / 2)  # Output: 5.0  

    Floor division (//) truncates the decimal part and returns an integer:

    print(10 // 3)  # Output: 3 (since 3 * 3 = 9 ≤ 10)  
    print(-10 // 3)  # Output: -4 (Python rounds down to the nearest integer)  
  • Modulus with Negative Numbers:
    The result of a % b has the same sign as b (the divisor):

    print(15 % 4)   # 15 = 3*4 + 3 → Output: 3 (same sign as 4)  
    print(-15 % 4)  # -15 = (-4)*4 + 1 → Output: 1 (same sign as 4)  
    print(15 % -4)  # 15 = (-4)*-4 + (-1) → Output: -1 (same sign as -4)  
  • Exponentiation:
    Use ** for powers, or pow() for larger exponents:

    print(2** 5)    # Output: 32  
    print(pow(3, 4))  # Output: 81 (equivalent to 3**4)  

2. Assignment Operators#

Assignment operators assign values to variables. The basic operator is =, but Python also supports compound assignment operators that combine an operation with assignment (e.g., +=, -=).

OperatorExampleEquivalent To
=x = 5x = 5
+=x += 3x = x + 3
-=x -= 2x = x - 2
*=x *= 4x = x * 4
/=x /= 2x = x / 2
//=x //= 3x = x // 3
%=x %= 5x = x % 5
**=x **= 3x = x ** 3

Example:#

x = 10  
x += 5  # x = x + 5 → x becomes 15  
x *= 2  # x = x * 2 → x becomes 30  
print(x)  # Output: 30  

3. Comparison Operators#

Comparison operators compare two values and return a Boolean result (True or False). They are critical for control flow (e.g., if statements, loops).

OperatorNameDescriptionExampleOutput
==Equal toChecks if values are equal5 == 5True
!=Not equal toChecks if values are not equal5 != 3True
>Greater thanChecks if left > right7 > 3True
<Less thanChecks if left < right2 < 5True
>=Greater than or equalChecks if left ≥ right4 >= 4True
<=Less than or equalChecks if left ≤ right3 <= 1False

Key Notes:#

  • String Comparison: Strings are compared lexicographically (based on Unicode values):

    print("apple" < "banana")  # True ("a" comes before "b")  
    print("Apple" < "apple")   # True ("A" has a lower Unicode value than "a")  
  • None Comparison: Use is (not ==) to check for None (see Identity Operators):

    x = None  
    print(x == None)  # Works but not recommended  
    print(x is None)  # Preferred (more explicit)  

4. Logical Operators#

Logical operators combine Boolean expressions to form complex conditions. Python supports and, or, and not.

OperatorNameDescription
andLogical ANDReturns True only if both operands are True
orLogical ORReturns True if at least one operand is True
notLogical NOTInverts the Boolean value of the operand

Short-Circuit Evaluation:#

Python uses short-circuiting to optimize logical operations:

  • and: Stops evaluating once a False operand is found (returns the first falsy value).
  • or: Stops evaluating once a True operand is found (returns the first truthy value).

Examples:#

# and: Returns first falsy value (0 is falsy)  
print(0 and 5)  # Output: 0  
 
# or: Returns first truthy value (5 is truthy)  
print(0 or 5)   # Output: 5  
 
# not: Inverts the value  
print(not True)  # Output: False  
print(not 0)     # Output: True (0 is falsy, so not 0 is True)  

Truthy vs. Falsy Values:#

In Python, values are considered "truthy" (evaluate to True) unless they are:

  • False
  • None
  • 0 (or 0.0, 0j)
  • Empty sequences ("", [], (), {})
  • Empty collections (set(), dict())

5. Bitwise Operators#

Bitwise operators manipulate integers at the bit level (binary representation). They are used in low-level programming, cryptography, and performance-critical applications.

OperatorNameDescriptionExample (Binary)Decimal Output
&Bitwise ANDSets each bit to 1 if both bits are 15 (101) & 3 (011)0011
``Bitwise ORSets each bit to 1 if at least one bit is 1`5 (101)
^Bitwise XORSets each bit to 1 if exactly one bit is 15 (101) ^ 3 (011)1106
~Bitwise NOTInverts all bits (two’s complement: ~x = -x - 1)~5 (00000101)11111010-6
<<Left ShiftShifts bits left by n positions (equivalent to x * 2^n)5 << 210100 (20)20
>>Right ShiftShifts bits right by n positions (equivalent to x // 2^n)20 >> 2101 (5)5

Example:#

a = 10  # Binary: 1010  
b = 4   # Binary: 0100  
 
print(a & b)   # 0000 → 0  
print(a | b)   # 1110 → 14  
print(a ^ b)   # 1110 → 14? Wait, 1010 ^ 0100 = 1110 (14). Correct.  
print(~a)      # -11 (since ~10 = -10 -1 = -11)  
print(a << 1)  # 10100 (20)  
print(a >> 2)  # 10 (2)  

6. Identity Operators#

Identity operators check if two variables point to the same object (i.e., share the same memory address). They are is and is not.

OperatorDescriptionExampleOutput
isReturns True if both variables are the same objectx is yTrue/False
is notReturns True if variables are different objectsx is not yTrue/False

Key Difference: == vs. is#

  • == checks if values are equal.
  • is checks if objects are identical (same memory address).

Example:#

x = [1, 2, 3]  
y = [1, 2, 3]  
z = x  
 
print(x == y)   # True (values are equal)  
print(x is y)   # False (different objects)  
print(x is z)   # True (same object)  

Note: Small Integer Interning#

Python "interns" small integers (-5 to 256) to save memory, so they reuse the same object:

a = 10  
b = 10  
print(a is b)  # True (same object)  
 
c = 257  
d = 257  
print(c is d)  # False (different objects in some Python implementations)  

7. Membership Operators#

Membership operators check if a value is present in a sequence (e.g., list, string, tuple) or collection (e.g., set, dictionary). They are in and not in.

OperatorDescriptionExampleOutput
inReturns True if value is in the sequence5 in [1, 2, 5]True
not inReturns True if value is not in the sequence5 not in [1, 2, 3]True

Examples:#

# Lists  
fruits = ["apple", "banana", "cherry"]  
print("banana" in fruits)  # True  
 
# Strings (checks for substring)  
text = "Hello, World!"  
print("World" in text)     # True  
 
# Dictionaries (checks for keys, not values)  
person = {"name": "Alice", "age": 30}  
print("name" in person)    # True  
print("Alice" in person)   # False (checks keys, not values)  

8. Operator Precedence#

When an expression has multiple operators, Python follows a precedence order to determine which operations to perform first. Use parentheses () to override precedence.

PrecedenceOperators
Highest() (parentheses)
** (exponentiation)
~, +, - (unary ops)
*, /, //, %
+, - (binary ops)
<<, >> (bitwise shifts)
& (bitwise AND)
^ (bitwise XOR)
`
==, !=, >, <, >=, <=
is, is not
in, not in
not
and
Lowestor

Example:#

# Without parentheses: 3 * 2 is evaluated first  
print(2 + 3 * 2)  # 2 + 6 = 8  
 
# With parentheses: 2 + 3 is evaluated first  
print((2 + 3) * 2)  # 5 * 2 = 10  

9. Advanced Topics#

Chained Comparisons#

Python allows chaining multiple comparisons for readability:

x = 5  
print(1 < x < 10)  # Equivalent to (1 < x) and (x < 10) → True  
print(10 < x < 20) # False  

Custom Operators (Operator Overloading)#

You can define custom behavior for operators in classes by overriding special methods (e.g., __add__ for +, __eq__ for ==).

Example: A Vector class with overloaded +:

class Vector:  
    def __init__(self, x, y):  
        self.x = x  
        self.y = y  
 
    def __add__(self, other):  
        return Vector(self.x + other.x, self.y + other.y)  
 
    def __repr__(self):  
        return f"Vector({self.x}, {self.y})"  
 
v1 = Vector(2, 3)  
v2 = Vector(4, 5)  
v3 = v1 + v2  
print(v3)  # Output: Vector(6, 8)  

10. Conclusion#

Operators are the backbone of Python programming, enabling everything from simple calculations to complex logic. By mastering arithmetic, assignment, comparison, logical, bitwise, identity, and membership operators, you’ll be able to write more expressive and efficient code. Remember operator precedence to avoid bugs, and experiment with custom operators to extend Python’s functionality.

Practice with real-world examples (e.g., calculating discounts, validating user input, or processing binary data) to solidify your understanding!

11. References#