Vasu Patel logoVasu Patel
← Python Syntax & DSA Reference
All chapters in this track
  1. 011. Variables, Types & Operators
  2. 022. Strings
  3. 033. Lists
  4. 044. Tuples, Sets & Dicts
  5. 055. Control Flow
  6. 066. Error Handling
  7. 077. Functions & Lambdas
  8. 088. Comprehensions
  9. 099. Built-in Functions
  10. 1010. Type Hints (3.10+)
  11. 1111. Classes & Dataclasses
  12. 1212. Iterators & Generators
  13. 1313. DSA Standard Library
  14. 1414. Python 3.9–3.11 Features for DSA
  15. 1515. DSA Idioms & Gotchas
  16. 1616. Master Quick Reference

Chapter 1 of 16

1. Variables, Types & Operators

Tutorial

Python is dynamically typed — variables hold references, not values of a fixed type. Python integers have arbitrary precision (no overflow), which makes DSA problems much simpler than in Java/C++.

# --- Variables ---
x: int   = 42
y: float = 3.14
s: str   = "hello"
flag: bool = True
nothing = None

# Multiple assignment (swap without temp — very common in DSA)
a, b = 1, 2
a, b = b, a   # swap in one line

# Augmented assignment
x += 1; x -= 1; x *= 2; x //= 3; x **= 2; x %= 7

# --- Integer precision (no overflow!) ---
n = 10 ** 18          # perfectly fine
big = 2 ** 200        # exact

factorial_100 = 1
for i in range(1, 101):
    factorial_100 *= i   # no overflow, exact result

# --- Integer division behaviour ---
7  // 2     #  3   (floor toward -∞, not truncation)
-7 // 2     # -4   (floor, not -3!)
7  %  2     #  1   (modulo always non-negative when divisor > 0)
-7 %  3     #  2   (Python's modulo, useful for circular index)

# --- Arithmetic operators ---
5 + 3     # 8
5 - 3     # 2
5 * 3     # 15
5 / 3     # 1.666...  (always float in Python 3)
5 // 3    # 1          floor division
5 % 3     # 2          modulo
5 ** 3    # 125        exponentiation

# --- Comparison operators (return True/False) ---
a == b    # equal
a != b    # not equal
a < b     # less than
a > b     # greater than
a <= b    # less than or equal
a >= b    # greater than or equal

# --- Bitwise operators (critical for DSA) ---
n & 1           # check odd (1) or even (0)
n & (n - 1)     # clear lowest set bit  (used in Fenwick tree)
n & (-n)        # isolate lowest set bit
n | (1 << k)    # set bit k
n ^ n           # always 0 (find non-duplicate)
1 << k          # 2^k (bitmask DP)
(mask >> i) & 1 # get bit i of mask

# Python 3.10+: int.bit_count() — number of set bits
(0b10110).bit_count()   # 3
n.bit_count()           # replaces bin(n).count('1')

# Example: check if n is a power of 2
def is_power_of_2(n: int) -> bool:
    return n > 0 and (n & (n - 1)) == 0

# --- Chained comparisons ---
0 <= i < n              # valid index check
lo <= val <= hi         # range check

# --- Logical operators ---
True and False   # False
True or False    # True
not True         # False

# Short-circuit evaluation — very common in DSA
node and node.val        # returns node.val if node is not None, else None
stack and stack[-1]      # safe peek: returns top of stack, or falsy if empty

# 'and'/'or' return the actual value, not just True/False
0 or 5             # 5    (returns first truthy value)
5 or 0             # 5
None or "default"  # "default"
[] or [1, 2]       # [1, 2]

# --- Truthiness (common in DSA guards) ---
# Falsy: 0, 0.0, "", [], {}, set(), None, False — everything else is truthy
if arr:        # non-empty list
if not arr:    # empty list
if node:       # node is not None
x or default   # returns default if x is falsy

Type Conversion

int("42")        # 42    — string to int
int("1010", 2)   # 10    — binary string to int (base 2)
int("ff", 16)    # 255   — hex string to int (base 16)
float("3.14")    # 3.14
str(42)          # "42"
bool(0)          # False
bool("")         # False
bool(1)          # True
list((1, 2, 3))  # [1, 2, 3]  — tuple to list
tuple([1, 2, 3]) # (1, 2, 3)  — list to tuple
set([1, 1, 2])   # {1, 2}     — list to set (removes duplicates)

# Type checking
type(x) == int              # check type
isinstance(x, int)          # preferred — True if x is int or subclass
isinstance(x, (int, float)) # check multiple types at once

Reference

OperationSyntaxNotes
Floor divisiona // bRounds toward −∞-\infty
Moduloa % bAlways ≥0\geq 0 when b > 0
Powera ** bExact; use pow(a,b,mod) for modular
Bitwise ANDa & b
Bitwise ORa | b
Bitwise XORa ^ b
Left/right shifta << n, a >> n
Set bit countn.bit_count()3.10+; replaces bin(n).count('1')
Check oddn & 1
Clear lowest bitn & (n-1)
Integer precisionunlimitedNo overflow in Python
Infinityfloat("inf")Comparable with any int
Chained comparea < x < bBoth conditions checked
String → intint(s, base)base defaults to 10
Type checkisinstance(x, T)Preferred over type(x) == T
Power-of-2 checkn & (n-1) == 0See is_power_of_2() above