Introduction to Python Operators
Learn all Python operator types — arithmetic, comparison, assignment, logical, bitwise, identity, and membership — with examples and precedence rules.
Operators are the symbols and keywords that tell Python what action to perform on one or more values. Every meaningful Python expression — from x + 1 to if age >= 18 — relies on at least one operator. Python groups its operators into seven categories: arithmetic, comparison, assignment, logical, identity, membership, and bitwise. This chapter explains each category, shows when to use it, and highlights common gotchas.
Arithmetic Operators
Arithmetic operators perform mathematical calculations. Python provides seven of them:
| Operator | Name | Example | Result |
|---|---|---|---|
+ | Addition | 17 + 5 | 22 |
- | Subtraction | 17 - 5 | 12 |
* | Multiplication | 17 * 5 | 85 |
/ | Division | 17 / 5 | 3.4 |
% | Modulus (remainder) | 17 % 5 | 2 |
** | Exponentiation | 2 ** 8 | 256 |
// | Floor division | 17 // 5 | 3 |
Two operators deserve extra attention:
/always returns afloatin Python 3, even when dividing two integers (4 / 2returns2.0, not2).//(floor division) rounds the result toward negative infinity, not toward zero. So-7 // 2is-4, not-3.
Common use: checking even or odd
The modulus operator (%) is the standard way to test divisibility:
number = 42
if number % 2 == 0:
print("even")
else:
print("odd")
# Output: evenComparison Operators
Comparison operators compare two values and always return True or False. They are used in conditions, while loops, and anywhere a Boolean result is needed.
| Operator | Meaning | Example | Result |
|---|---|---|---|
== | Equal to | 5 == 5 | True |
!= | Not equal to | 5 != 3 | True |
> | Greater than | 5 > 3 | True |
< | Less than | 5 < 3 | False |
>= | Greater than or equal to | 5 >= 5 | True |
<= | Less than or equal to | 5 <= 4 | False |
Chaining comparisons
Python lets you chain multiple comparisons in one expression, which reads more naturally than in most other languages:
x = 7
print(1 < x < 10) # True — equivalent to (1 < x) and (x < 10)
print(0 < x < 5) # FalseGotcha: == vs =
= is the assignment operator; == tests equality. Using = inside a condition is a SyntaxError in Python (unlike some other languages where it silently assigns).
Assignment Operators
Assignment operators store values in variables. The compound forms (+=, -=, …) combine an arithmetic or bitwise operation with assignment, making the code more concise.
| Operator | Equivalent to | Example |
|---|---|---|
= | — | x = 10 |
+= | x = x + n | x += 3 |
-= | x = x - n | x -= 3 |
*= | x = x * n | x *= 3 |
/= | x = x / n | x /= 3 |
//= | x = x // n | x //= 3 |
%= | x = x % n | x %= 3 |
**= | x = x ** n | x **= 3 |
&= | x = x & n | x &= 0b1111 |
|= | x = x | n | x |= 0b1000 |
^= | x = x ^ n | x ^= 0b0101 |
<<= | x = x << n | x <<= 1 |
>>= | x = x >> n | x >>= 1 |
The walrus operator := (Python 3.8+)
The walrus operator assigns a value inside an expression. It is useful when you want to both evaluate and store a result without writing the expression twice:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Without walrus: compute length twice
if len(numbers) > 5:
print(f"Long list: {len(numbers)} items")
# With walrus: assign once, use in condition and body
if (n := len(numbers)) > 5:
print(f"Long list: {n} items")
# Output: Long list: 10 itemsLogical Operators
Logical operators combine or invert Boolean expressions. Python uses English keywords rather than symbols (&&, ||, !).
| Operator | Meaning | Example | Result |
|---|---|---|---|
and | True if both sides are true | True and False | False |
or | True if at least one side is true | True or False | True |
not | Inverts the Boolean value | not True | False |
Short-circuit evaluation
Python evaluates and and or lazily (left to right) and stops as soon as the result is determined:
False and <anything>— the right side is never evaluated.True or <anything>— the right side is never evaluated.
This matters when the right-hand side has a side effect or could raise an error:
user_input = ""
name = user_input or "Anonymous"
print(name) # Anonymous (empty string is falsy, so "Anonymous" is returned)Truthy and falsy values
Logical operators work with any value, not just True/False. Python treats 0, "", None, [], {}, and () as falsy; everything else is truthy.
See the Python Data Types chapter for a full list of falsy values per type.
Identity Operators
Identity operators test whether two variables point to the same object in memory, not just whether they hold equal values.
| Operator | Meaning |
|---|---|
is | True if both variables reference the same object |
is not | True if they reference different objects |
When to use is vs ==
Use is only when you intentionally want to check object identity — most commonly when comparing to singletons:
value = None
if value is None: # correct idiom
print("No value provided")
# Never do: if value == None — works but is considered bad stylePython caches small integers (typically -5 to 256) and interned strings, so a is b may return True for two separately created small integers. Never rely on this behavior for integers or strings — use == for value equality.
Membership Operators
Membership operators test whether a value exists inside a sequence (list, tuple, string, set, or dictionary).
| Operator | Meaning |
|---|---|
in | True if the value is found in the sequence |
not in | True if the value is not found |
Performance note
For lists and tuples, in checks every element sequentially (O(n)). For sets and dictionary keys, in uses a hash table and runs in constant time (O(1)). Prefer a set when you need many membership tests on a large collection.
Bitwise Operators
Bitwise operators work on the binary representation of integers, manipulating individual bits.
| Operator | Name | Example | Result | Notes |
|---|---|---|---|---|
& | AND | 5 & 3 | 1 | Bit is 1 only if both bits are 1 |
| | OR | 5 | 3 | 7 | Bit is 1 if either bit is 1 |
^ | XOR | 5 ^ 3 | 6 | Bit is 1 if bits differ |
~ | NOT | ~5 | -6 | Inverts all bits; result is -(n+1) |
<< | Left shift | 5 << 1 | 10 | Shifts bits left (multiply by 2) |
>> | Right shift | 20 >> 2 | 5 | Shifts bits right (divide by 2) |
Why bitwise operators matter
In most everyday Python code you will not use bitwise operators directly, but they appear frequently in:
- Flags and permissions — combining bitmasks to represent multiple options in a single integer.
- Cryptography and hashing — XOR is a basic building block.
- Efficient math —
n << 1is faster thann * 2in performance-critical loops. - Working with binary protocols — parsing network packets or file headers.
Operator Precedence
When an expression mixes several operators, Python evaluates them in a fixed order (highest precedence first):
| Priority | Operators |
|---|---|
| 1 (highest) | ** |
| 2 | +x, -x, ~x (unary) |
| 3 | *, /, //, % |
| 4 | +, - |
| 5 | <<, >> |
| 6 | & |
| 7 | ^ |
| 8 | | |
| 9 | ==, !=, <, >, <=, >=, is, is not, in, not in |
| 10 | not |
| 11 | and |
| 12 (lowest) | or |
# Multiplication before addition (standard math rules apply)
print(2 + 3 * 4) # 14, not 20
# Use parentheses to override
print((2 + 3) * 4) # 20
# ** is right-associative: 2 ** 3 ** 2 = 2 ** (3**2) = 2**9
print(2 ** 3 ** 2) # 512, not 64
# Comparisons before logical operators
print(2 + 3 > 4 and 10 % 3 == 1) # True and True → TrueWhen in doubt, use parentheses. They make precedence explicit and improve readability.
Summary
| Category | Operators | Primary use |
|---|---|---|
| Arithmetic | + - * / % ** // | Math calculations |
| Comparison | == != > < >= <= | Conditions, filtering |
| Assignment | = += -= *= /= //= %= **= &= |= ^= <<= >>= | Store and update variables |
| Logical | and or not | Combining Boolean conditions |
| Identity | is is not | Singleton checks (e.g. is None) |
| Membership | in not in | Searching sequences and sets |
| Bitwise | & | ^ ~ << >> | Binary flags, low-level data |
For related topics, see Python Variables, Python If...Else, and Python Data Types.