Skip to content

Latest commit

 

History

History
572 lines (440 loc) · 17.7 KB

05_operators.md

File metadata and controls

572 lines (440 loc) · 17.7 KB

05 — Operators

"Operators are the verbs of Python — they make things happen."


Table of Contents


Arithmetic Operators

a, b = 17, 5

print(a + b)    # 22  — Addition
print(a - b)    # 12  — Subtraction
print(a * b)    # 85  — Multiplication
print(a / b)    # 3.4 — True Division (always returns float)
print(a // b)   # 3   — Floor Division (rounds DOWN to integer)
print(a % b)    # 2   — Modulo (remainder)
print(a ** b)   # 1419857 — Exponentiation

# Important edge cases
print(7 / 2)    # 3.5  (true division in Python 3)
print(7 // 2)   # 3    (floor division)
print(-7 // 2)  # -4   ← floor division rounds toward -infinity!
print(7 % 3)    # 1
print(-7 % 3)   # 2    ← result takes sign of divisor in Python

# Practical use of %
# Check even/odd
print(10 % 2 == 0)  # True — even
print(11 % 2 == 0)  # False — odd

# Cycles (clock arithmetic)
hour = (12 + 5) % 12   # 5 (wraps around 12-hour clock)
day = (6 + 3) % 7      # 2 (wraps around days of week)

Comparison Operators

Return a boolean (True or False).

a, b = 10, 20

print(a == b)   # False — Equal to
print(a != b)   # True  — Not equal to
print(a < b)    # True  — Less than
print(a > b)    # False — Greater than
print(a <= b)   # True  — Less than or equal to
print(a >= b)   # False — Greater than or equal to

# Chained comparisons (Python unique feature!)
x = 15
print(10 < x < 20)         # True  — much cleaner than Java!
print(0 <= x <= 100)        # True
print(1 < 2 < 3 < 4 < 5)   # True

# String comparisons (lexicographic — based on Unicode values)
print("apple" < "banana")   # True (a < b alphabetically)
print("Z" < "a")            # True (uppercase Z=90 < lowercase a=97)
print("abc" == "abc")       # True

# List comparisons (element by element)
print([1, 2, 3] == [1, 2, 3])  # True
print([1, 2, 3] < [1, 2, 4])   # True (compares element by element)

Logical Operators

Combine boolean expressions. Implement short-circuit evaluation.

# and — True only if BOTH are True
print(True and True)    # True
print(True and False)   # False
print(False and True)   # False (short-circuits — doesn't check right side!)

# or — True if AT LEAST ONE is True
print(True or False)    # True (short-circuits — doesn't check right side!)
print(False or False)   # False
print(False or True)    # True

# not — inverts boolean value
print(not True)         # False
print(not False)        # True
print(not 0)            # True
print(not "hello")      # False

# Short-circuit evaluation — VERY important concept
x = 10
print(x > 5 and x < 20)   # True — both evaluated
print(x > 20 and x < 30)  # False — right side NOT evaluated (short-circuit)
print(x > 20 or x < 15)   # True — right side IS evaluated

# Practical: default value pattern using 'or'
name = ""
display_name = name or "Anonymous"    # If name is falsy, use "Anonymous"
print(display_name)   # Anonymous

name = "Logesh"
display_name = name or "Anonymous"
print(display_name)   # Logesh

# Better way (Python 3.8+): walrus operator
if (n := len(name := input("Name: "))) > 3:
    print(f"Name '{name}' has {n} characters")

# Logical operators with non-boolean values (returns one of the operands!)
print(3 and 5)       # 5   — returns last evaluated value (both truthy)
print(0 and 5)       # 0   — returns first falsy value (short-circuits)
print(3 or 5)        # 3   — returns first truthy value (short-circuits)
print(0 or 5)        # 5   — first is falsy, returns second
print(0 or "" or []) # []  — all falsy, returns last value

Assignment Operators

x = 10          # Basic assignment

# Augmented assignment operators
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  (becomes float!)
x //= 2         # x = x // 2  → 3.0  (floor, but still float since x was float)
x **= 3         # x = x ** 3  → 27.0
x %= 5          # x = x % 5   → 2.0

# Bitwise augmented
x = 0b1010
x &= 0b1100     # Bitwise AND assign
x |= 0b0001     # Bitwise OR assign
x ^= 0b1111     # Bitwise XOR assign
x <<= 1         # Left shift assign
x >>= 1         # Right shift assign

# Walrus operator := (Python 3.8+) — assign AND use in expression
import re
data = "Phone: 9876543210"
if match := re.search(r'\d{10}', data):
    print(f"Found phone: {match.group()}")  # Found phone: 9876543210

# Useful in while loops
while chunk := file_obj.read(8192):  # Read and check in one step
    process(chunk)

Bitwise Operators

Work on binary representations of integers.

a = 0b1010   # 10 in decimal
b = 0b1100   # 12 in decimal

# AND — bit is 1 only if BOTH bits are 1
print(a & b)    # 0b1000 = 8
# 1010
# 1100
# ----
# 1000

# OR — bit is 1 if EITHER bit is 1
print(a | b)    # 0b1110 = 14
# 1010
# 1100
# ----
# 1110

# XOR — bit is 1 if bits are DIFFERENT
print(a ^ b)    # 0b0110 = 6
# 1010
# 1100
# ----
# 0110

# NOT — flip all bits (returns -(n+1))
print(~a)       # -11  (inverts all bits, including sign bit)

# LEFT SHIFT — multiply by 2^n
print(a << 1)   # 0b10100 = 20  (multiply by 2)
print(a << 2)   # 0b101000 = 40 (multiply by 4)

# RIGHT SHIFT — divide by 2^n
print(a >> 1)   # 0b101 = 5  (divide by 2)
print(a >> 2)   # 0b10  = 2  (divide by 4)

# Practical uses of bitwise operators
# 1. Check if number is even (last bit is 0)
print(10 & 1 == 0)   # True — even
print(7  & 1 == 0)   # False — odd

# 2. Fast multiply/divide by powers of 2
n = 5
print(n << 3)    # 40  (5 * 8)
print(n >> 1)    # 2   (5 // 2)

# 3. Swap without temp variable using XOR
x, y = 10, 20
x ^= y
y ^= x
x ^= y
print(x, y)  # 20 10

# 4. Create and check bitmask flags
READ    = 0b001   # 1
WRITE   = 0b010   # 2
EXECUTE = 0b100   # 4

permissions = READ | WRITE  # 0b011 = 3 (can read AND write)
print(permissions & READ != 0)    # True  — has READ
print(permissions & EXECUTE != 0) # False — no EXECUTE

Identity Operators — is

is checks if two variables point to the SAME object in memory. This is different from == which checks VALUE equality.

# is — True if same object (same memory address)
# is not — True if different objects

a = [1, 2, 3]
b = [1, 2, 3]
c = a

print(a == b)    # True  — same values
print(a is b)    # False — different objects in memory!
print(a is c)    # True  — c is literally 'a' (same object)

# Check memory addresses
print(id(a))     # e.g., 1234567890
print(id(b))     # e.g., 9876543210  (different!)
print(id(c))     # same as id(a)

# 'is not' — opposite of 'is'
print(a is not b)   # True
print(a is not c)   # False

When to Use is

# ✅ ALWAYS use 'is' for None checks
result = None
if result is None:
    print("No result")

if result is not None:
    print(f"Result: {result}")

# ❌ Don't do this (works but is bad practice):
if result == None:   # Works but a linter will warn you
    pass

# ✅ Use 'is' for True/False checks (rare — usually just use truthiness)
flag = True
if flag is True:     # Strict — only matches True, not 1 or "hello"
    pass
if flag:             # Pythonic — matches any truthy value
    pass

# ⚠️ NEVER use 'is' for comparing strings or numbers (unreliable!)
# Due to Python's interning/caching, it MIGHT work for small numbers
# and simple strings — but this is an IMPLEMENTATION DETAIL, not guaranteed!
x = 1000
y = 1000
print(x == y)    # ✅ True — always reliable
print(x is y)    # ⚠️ Might be True or False depending on Python version/context

Integer Caching (Why is Surprises People)

# Python caches integers from -5 to 256
a = 100
b = 100
print(a is b)   # True  — same cached object

a = 1000
b = 1000
print(a is b)   # False — different objects (outside cache range)

# String interning
s1 = "hello"
s2 = "hello"
print(s1 is s2)     # True  — Python interns simple string literals

s3 = "hello world"
s4 = "hello world"
print(s3 is s4)     # May be True or False — don't rely on this!

Membership Operators — in

in tests if a value EXISTS within a sequence or collection. not in tests if a value does NOT exist.

# in — True if item is found
fruits = ["apple", "banana", "cherry"]

print("apple" in fruits)       # True
print("mango" in fruits)       # False
print("apple" not in fruits)   # False
print("mango" not in fruits)   # True

in with Different Data Structures

# List — O(n) linear search
colors = ["red", "green", "blue"]
print("red" in colors)          # True  (scans from start)

# Tuple — O(n) linear search
nums = (1, 2, 3, 4, 5)
print(3 in nums)                # True

# String — substring check O(n)
sentence = "Python is awesome"
print("Python" in sentence)     # True
print("Java" in sentence)       # False
print("is" in sentence)         # True

# Set — O(1) hash lookup (MUCH faster than list for large data!)
large_set = set(range(1_000_000))
print(999_999 in large_set)     # True  — instant! O(1)

large_list = list(range(1_000_000))
print(999_999 in large_list)    # True  — slow! O(n)

# Dictionary — checks KEYS by default
person = {"name": "Logesh", "age": 22, "city": "Chennai"}
print("name" in person)         # True  — checks keys
print("Logesh" in person)       # False — "Logesh" is a value, not a key

# Check values explicitly
print("Logesh" in person.values())   # True
print(("name", "Logesh") in person.items())  # True — check key-value pair

Practical Patterns with in

# Guard clause pattern
valid_roles = {"admin", "editor", "viewer"}
user_role = "admin"

if user_role not in valid_roles:
    raise ValueError(f"Invalid role: {user_role}")

print(f"Access granted for: {user_role}")

# Multiple membership check
vowels = set("aeiou")
word = "python"
has_vowel = any(c in vowels for c in word)
print(has_vowel)   # True ('o' is in word)

all_vowel = all(c in vowels for c in "aei")
print(all_vowel)   # True

# Filtering with 'in'
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
targets = {2, 4, 6, 8, 10}
evens_in_target = [n for n in numbers if n in targets]
print(evens_in_target)  # [2, 4, 6, 8, 10]

Performance: in on Different Structures

Structure in Complexity Notes
list O(n) Scans linearly
tuple O(n) Same as list
set O(1) average Hash table lookup
dict O(1) average Hash table on keys
str O(n) Substring search
# Always use set for repeated membership testing!
# Bad:
allowed = ["GET", "POST", "PUT", "DELETE"]
method = "POST"
if method in allowed:    # O(n) every call
    pass

# Good:
ALLOWED_METHODS = {"GET", "POST", "PUT", "DELETE"}  # set
if method in ALLOWED_METHODS:  # O(1) every call
    pass

Operator Precedence

Higher precedence operations are evaluated first (like BODMAS/PEMDAS).

Precedence Operator Description
Highest () Parentheses
** Exponentiation
+x, -x, ~x Unary operators
*, /, //, % Multiplication/Division
+, - Addition/Subtraction
<<, >> Bitwise shifts
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
==, !=, <, >, <=, >=, is, is not, in, not in Comparisons
not Logical NOT
and Logical AND
Lowest or Logical OR
# Examples
print(2 + 3 * 4)       # 14  (not 20 — * before +)
print((2 + 3) * 4)     # 20  (parentheses first)
print(2 ** 3 ** 2)     # 512 (** is right-associative: 3**2=9, then 2**9)
print(10 - 2 + 3)      # 11  (left-to-right for same precedence)

# Tricky
print(not True and False)     # False  (not has higher precedence than and)
# Equivalent to: (not True) and False → False and False → False

print(not (True and False))   # True   (parentheses change everything)

Useful Built-in Functions with Operators

# divmod(a, b) — returns (quotient, remainder) as a tuple in one call
print(divmod(17, 5))   # (3, 2)  → 17 // 5 = 3, 17 % 5 = 2
print(divmod(100, 7))  # (14, 2)

# Useful for converting seconds to hours/minutes/seconds
total_seconds = 3672
hours, remainder = divmod(total_seconds, 3600)
minutes, seconds = divmod(remainder, 60)
print(f"{hours}h {minutes}m {seconds}s")   # 1h 1m 12s

# pow(base, exp, mod) — faster modular exponentiation
print(pow(2, 10))        # 1024
print(2 ** 10)           # 1024 (same)
print(pow(2, 10, 1000))  # 24 — (2**10) % 1000, much faster than (2**10) % 1000 for large nums
# Critical for cryptography (RSA uses this!)
print(pow(base, exp, mod))  # Built-in is MUCH faster for large numbers

# abs() — absolute value (works for int, float, complex)
print(abs(-42))        # 42
print(abs(-3.14))      # 3.14
print(abs(3 + 4j))     # 5.0 (magnitude of complex number)

# round() — round to N decimal places
print(round(3.14159, 2))  # 3.14
print(round(2.5))         # 2  ← Banker's rounding! (rounds to even)
print(round(3.5))         # 4
print(round(1234, -2))    # 1200 (round to nearest 100)

operator Module — Functional Operators

import operator

# operator module has functions for each operator
print(operator.add(3, 4))        # 7   (same as 3 + 4)
print(operator.sub(10, 3))       # 7
print(operator.mul(3, 4))        # 12
print(operator.truediv(10, 3))   # 3.333...
print(operator.floordiv(10, 3))  # 3
print(operator.mod(10, 3))       # 1
print(operator.pow(2, 8))        # 256
print(operator.neg(-5))          # 5

# Comparison
print(operator.eq(1, 1))         # True
print(operator.lt(1, 2))         # True
print(operator.ge(3, 3))         # True

# Why use operator module? — Passes operators as arguments to functions!
from functools import reduce

nums = [1, 2, 3, 4, 5]
print(reduce(operator.add, nums))  # 15 (cleaner than lambda x, y: x + y)
print(reduce(operator.mul, nums))  # 120

# operator.itemgetter — get item by key (faster than lambda for sorting)
students = [{"name": "Bob", "grade": 85}, {"name": "Alice", "grade": 90}]
students.sort(key=operator.itemgetter("grade"))
print(students[0]["name"])  # Bob

# operator.attrgetter — get object attribute
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

people = [Person("Bob", 30), Person("Alice", 25)]
people.sort(key=operator.attrgetter("age"))
print(people[0].name)   # Alice

Interview Q&A

Q1: What is the difference between == and is?

== checks value equality (do they have the same value?). is checks object identity (are they the exact same object in memory?). Use is only for None, True, and False comparisons. Always use == for value comparisons.

Q2: Why does x = 1000; y = 1000; print(x is y) sometimes print False?

Python caches (interns) small integers from -5 to 256 for performance. For values outside this range, each assignment creates a new integer object. So x and y are different objects, even though they have the same value. This is why you should never use is to compare numbers.

Q3: What is short-circuit evaluation?

In A and B, if A is False, Python skips evaluating B (result is already False). In A or B, if A is True, Python skips evaluating B. This is useful for things like: if obj is not None and obj.value > 0: — safe because obj.value is only checked if obj is not None.

Q4: Why is in faster with a set than a list?

A set uses a hash table internally. Checking membership is O(1) — it computes the hash of the item and directly checks that slot. A list must scan every element — O(n). For 1 million items: set is ~microseconds, list is ~milliseconds.

Q5: What does not in return?

It returns True if the item is NOT present in the collection, False if it IS present. It's equivalent to not (x in collection) but more readable.

Q6: What is the result of 3 and 5?

5. Logical operators in Python return one of the operands, not necessarily True or False. and returns the first falsy value, or the last value if all are truthy. or returns the first truthy value, or the last value if all are falsy.

Q7: What is divmod() and when would you use it?

divmod(a, b) returns (a // b, a % b) — the quotient and remainder as a tuple in one efficient call. Use it when you need both values (e.g., converting total seconds to hours/minutes/seconds).

Q8: What does pow(base, exp, mod) do?

It computes (base ** exp) % mod efficiently using modular exponentiation. It's much faster than (base ** exp) % mod for large numbers because it avoids computing the huge intermediate value. Used in cryptography (RSA algorithm).

Q9: What is operator overloading?

It's defining how built-in operators (+, -, *, ==, etc.) behave for custom objects, using dunder methods: __add__, __sub__, __eq__, etc. Python calls these automatically when you use the operator on your class instances.

Q10: What is the walrus operator and when should you avoid it?

:= (walrus) assigns and returns a value in one expression. Avoid it when it reduces readability — it's best used in while loops and if conditions where you'd otherwise compute the same value twice. Don't use it just to make code shorter if it makes it harder to read.


Next: 06 — Control Flow →