0%

24- Commonly Used Python Operators

Arithmetic, comparison, logical, assignment, membership, identity. The complete guide to Python’s operators. Master the symbols that make Python work.

Operators are the verbs of programming. They take values, perform actions, and produce results. Addition. Comparison. Assignment. Membership. Identity. Each operator has a purpose. Each follows specific rules. You have already seen many operators throughout this course. + for addition. == for equality. and for logical operations. But there are more. Some you know. Some you have seen briefly. Some are hidden gems. This lesson brings together all of Python’s commonly used operators in one place. Think of it as a reference guide. A map of the symbols you will encounter every day as a Python programmer.

🕯️ Magic Note

Python operators are actually special methods in disguise. When you write a + b, Python calls a.__add__(b) behind the scenes. This means you can define how operators work for your own classes. This is called operator overloading, and it is one of Python’s powerful features.

Arithmetic Operators
These perform mathematical calculations. You use them constantly.
OperatorNameExampleResult
+Addition10 + 313
Subtraction10 – 37
*Multiplication10 * 330
/Division (float)10 / 33.333…
//Floor division10 // 33
%Modulus (remainder)10 % 31
**Exponentiation (power)10 ** 31000

Python

a = 10

b = 3

print(a + b) # 13

print(a – b) # 7

print(a * b) # 30

print(a / b) # 3.3333333333333335

print(a // b) # 3

print(a % b) # 1

print(a ** b) # 1000

💡 Remember: / always returns a float. // returns an integer (floor division). For negative numbers, // floors down (toward negative infinity), not toward zero.
Comparison (Relational) Operators
These compare values and return True or False. The foundation of decision-making.
OperatorNameExampleResult
==Equal to5 == 5True
!= Not equal to5 != 3True
>Greater than5 > 3True
<Less than5 < 3False
>=Greater than or equal to5 >= 5True
<=Less than or equal to5 <= 3False

Python

x = 10

y = 20

print(x == y) # False

print(x != y) # True

print(x > y) # False

print(x < y) # True

print(x >= 10) # True

print(y <= 10) # False

⚠️ Do not confuse = (assignment) with == (comparison). if x = 5: is a syntax error. if x == 5: is correct.
Logical Operators
Combine boolean values. Used in complex conditions.
OperatorWhat It DoesExample (a=Trueb=False)Result
andTrue only if both are Truea and bFalse
orTrue if at least one is Truea or bTrue
notReverses the valuenot aFalse

Python

is_weekend = True

has_time = False

print(is_weekend and has_time) # False

print(is_weekend or has_time) # True

print(not is_weekend) # False

🕯️ Magic Note

and and or short-circuit. and stops at the first False. or stops at the first True. This can be used for conditional execution.

Assignment Operators
These assign values to variables. The simple = is the most common. The augmented operators combine assignment with another operation.
OperatorExampleEquivalent to
=x = 5x = 5
+=x += 3x = x + 3
-=x -= 3x = x – 3
*=x *= 3x = x * 3
/=x /= 3x = x / 3
//=x //= 3x = x // 3
%=x %= 3x = x % 3
**=x **= 3x = x ** 3

Python

counter = 0

counter += 1 # counter becomes 1

counter += 1 # counter becomes 2

score = 10

score *= 2 # score becomes 20

value = 100

value //= 3 # value becomes 33

Membership Operators
Check if a value exists in a sequence (list, tuple, string, set, dictionary). Very useful and readable.
OperatorExampleResult
in5 in [1, 2, 3, 4, 5]True
not in5 not in [1, 2, 3, 4]True

Python

fruits = [“apple”, “banana”, “cherry”]

print(“banana” in fruits) # True

print(“grape” in fruits) # False

print(“grape” not in fruits) # True

text = “Hello, World!”

print(“World” in text) # True

person = {“name”: “Ali”, “age”: 25}

print(“name” in person) # True (checks keys)

print(“Ali” in person) # False (checks keys, not values)

💡 For dictionaries, in checks keys, not values. Use “Ali” in person.values() to check values.
Identity Operators
Check if two variables refer to the same object in memory. Different from == which checks value equality.
OperatorExampleResult
isa is bTrue if same object
is nota is not bTrue if different objects

Python

a = [1, 2, 3]

b = [1, 2, 3]

c = a

print(a == b) # True (same values)

print(a is b) # False (different objects)

print(a is c) # True (same object)

x = 5

y = 5

print(x is y) # True (small integers are cached, but don’t rely on this)

⚠️ Use is for None, True, and False. Use == for everything else. Do not rely on integer or string interning.
Bitwise Operators (Advanced)
These work on the binary representation of numbers. Less common in everyday Python, but useful for flags, permissions, and low-level programming.
OperatorNameExample (x=5=0b0101 , y=3=0b0011)Result
&Bitwise ANDx & y1 (0b0001)
|Bitwise ORx | y7 (0b0111)
^Bitwise XORx ^ y6 (0b0110)
~Bitwise NOT~x-6
<<Left shiftx << 110 (0b1010)
>>Right shiftx >> 12 (0b0010)

Python

x = 5 # 0b0101

y = 3 # 0b0011

print(x & y) # 1 (0b0001)

print(x | y) # 7 (0b0111)

print(x ^ y) # 6 (0b0110)

print(~x) # -6

print(x << 1) # 10 (0b1010)

print(x >> 1) # 2 (0b0010)

💡 Bitwise operators are useful for working with flags, permissions (like Unix chmod), and optimizing certain calculations. Most Python code does not need them, but they are good to recognize.
Operator Precedence (Order of Operations)
When multiple operators appear in an expression, Python follows a specific order. Use parentheses to make your intent clear.
Precedence (High to Low)Operators
1 (highest)() (parentheses)
2** (exponentiation)
3~ (bitwise NOT), + (unary), (unary)
4*, /, //, %
5+, (binary)
6<<, >>
7&
8^
9|
10in, not in, is, is not, <, <=, >, >=, != , ==
11not (logical)
12and
13 (lowest)or

Python

# Without parentheses (follows precedence)

result = 10 + 3 * 2 # 10 + (3 * 2) = 16

# With parentheses (overrides precedence)

result = (10 + 3) * 2 # 13 * 2 = 26

# Complex example

a = 5

b = 10

c = 15

print(a < b and b < c) # True (and has lower precedence than comparison)

🕯️ Magic Note

When in doubt, use parentheses. They make your code more readable and remove any ambiguity about operator precedence. There is no performance penalty for extra parentheses.

The Walrus Operator (:=)
Introduced in Python 3.8. Assigns a value and returns it in a single expression. Useful for avoiding repeated computations.

Python

# Without walrus (compute twice)

data = [1, 2, 3, 4, 5]

if len(data) > 3:

print(f”List has {len(data)} items”) # len() called again

# With walrus (compute once)

if (n := len(data)) > 3:

print(f”List has {n} items”)

# In a while loop

while (line := input()) != “quit”:

print(f”You said: {line}”)

💡 The walrus operator is useful but controversial. Use it sparingly. If it makes code less readable, use a regular assignment instead.
Summary Table of Operators by Category
CategoryOperators
Arithmetic+, , *, /, //, %, **
Comparison==, != , >, <, >=, <=
Logicaland, or, not
Assignment=, +=, -=, *=, /=, //=, %=, **=
Membershipin, not in
Identityis, is not
Bitwise&, |, ^, ~, <<, >>
Walrus:=
Common Mistakes with Operators
  • Confusing = with ==
  • Using is instead of == for value comparison
  • Forgetting operator precedence and getting unexpected results
  • Using and and or with non-boolean values (works but may confuse)
  • Misunderstanding // with negative numbers
  • Using in with dictionaries and expecting value check (checks keys)
Check Your Understanding
  • What is the difference between = and ==?
  • What does // do? Give an example with negative numbers.
  • What is the result of 5 in [1, 2, 3, 4, 5]?
  • When should you use is instead of ==?
  • What is operator precedence?
  • What does the walrus operator := do?

⚡ Whisper

Operators are the small symbols that hold great power. A plus sign adds. An equals sign assigns. Two equals signs compare. A single ampersand reaches into the binary heart of a number. Each operator is a verb, an action, a tiny spell. Learn them one by one. The arithmetic operators are your first friends. The comparison operators become your judges. The logical operators become your decision-makers. The membership and identity operators become your seekers. And the assignment operator becomes your memory. Together, they form the language of computation. You do not need to memorize the precedence table. Parentheses are free. Use them. Write clearly. The computer will understand. More importantly, other humans will understand. That is the real magic of operators: not what they do, but how clearly they express your intent.

Related posts