ArbindBuilds LogoArbindBuilds
Blog
CheatsheetsProjectsLinksAbout
Hire Me

ArbindBuilds

Build. Design. Repeat.

© 2026 ArbindBuilds.
All rights reserved.

Site Map

  • Home
  • Blog
  • Projects
  • About
  • Uses

Content

  • Cheatsheets
  • AI Tools
  • AI Prompts
  • Links

Products

  • Speakify
  • Gumroad Store
  • GitHub
  • Twitter / X

Made with care in Assam, India.

  1. Home/
  2. Cheatsheets/
  3. Python Developer Cheatsheet

Python Developer Cheatsheet

A dense, no-fluff reference card for Python syntax, builtins, data structures, and patterns — 10 sections, zero padding.

ArbindBuilds·May 21, 2026·
pythoncheatsheetdeveloper-referencesyntaxbackendscripting

Data Types & Literals

TypeExample
int42, -7, 0b1010, 0xFF
float3.14, 1e-4, float('inf')
str"hi", f"x={x}", r"\n"
boolTrue, False (subclass of int)
NoneTypeNone
bytesb"data", bytes(4)
complex3+4j

Collections

TypeMutableOrderedUniqueLiteral
listyesyesno[1, 2]
tuplenoyesno(1, 2)
dictyesyes (3.7+)keys{"a": 1}
setyesnoyes{1, 2}
frozensetnonoyesfrozenset({1})
  • Empty set: set() — NOT {} (that's a dict)
  • Dict merge (3.9+): a | b

Comprehensions

# List
squares = [x**2 for x in range(10) if x % 2 == 0]

# Dict
inv = {v: k for k, v in original.items()}

# Set
unique_lens = {len(w) for w in words}

# Generator (lazy, no brackets)
total = sum(x**2 for x in range(1000))

# Nested
flat = [x for row in matrix for x in row]

Functions & Signatures

def fn(pos, /, normal, *, kw_only, kw_default=1, **kwargs):
    ...

# /  = positional-only before it
# *  = keyword-only after it
# *args / **kwargs = variadic

# Lambda
double = lambda x: x * 2

# Walrus operator (3.8+)
if n := len(data):
    print(n)

# Unpacking
a, *rest, z = [1, 2, 3, 4, 5]

Common Builtins

FunctionUse
enumerate(it)index + value pairs
zip(a, b)parallel iteration
map(fn, it)lazy transform
filter(fn, it)lazy filter
sorted(it, key=fn)returns new sorted list
any(it) / all(it)short-circuit bool checks
isinstance(x, T)type check (accepts tuple of types)
getattr(obj, 'k', default)safe attribute access

String Operations

s = "  Hello, World!  "

s.strip()            # "Hello, World!"
s.lower() / s.upper()
s.split(", ")        # ["Hello", "World!  "]
", ".join(["a","b"]) # "a, b"
s.replace("o", "0")
s.startswith("Hello") / s.endswith("!")
f"{42:>10.2f}"       # right-align, 2 decimal places
"sub" in s           # membership test

Error Handling

try:
    result = risky()
except (ValueError, TypeError) as e:
    log(e)
except Exception:
    raise          # re-raise without losing traceback
else:
    process(result)  # runs only if no exception
finally:
    cleanup()        # always runs

# Custom exception
class AppError(Exception):
    def __init__(self, msg, code):
        super().__init__(msg)
        self.code = code

Itertools Essentials

from itertools import (
    chain,        # chain([1,2], [3,4]) -> 1 2 3 4
    islice,       # islice(gen, 5) -> first 5
    groupby,      # group sorted iterable by key
    product,      # cartesian product
    combinations, # nCr combos, no repeat
    permutations, # nPr, ordered
    count,        # count(10) -> 10 11 12 ...
    cycle,        # cycle("AB") -> A B A B ...
)

File & Path I/O

from pathlib import Path

p = Path("data/input.txt")
p.exists() / p.is_file() / p.is_dir()
p.stem          # "input"
p.suffix        # ".txt"
p.parent        # Path("data")
list(p.parent.glob("*.csv"))

# Read / write
text = p.read_text(encoding="utf-8")
p.write_text("content")

# Context manager (large files)
with open(p, "r") as f:
    for line in f:
        process(line.rstrip())

Decorators & Context Managers

from functools import wraps, lru_cache, partial
from contextlib import contextmanager

# Memoize
@lru_cache(maxsize=128)
def fib(n): return n if n < 2 else fib(n-1)+fib(n-2)

# Custom decorator
def timer(fn):
    @wraps(fn)
    def wrapper(*args, **kwargs):
        t = time.perf_counter()
        result = fn(*args, **kwargs)
        print(f"{fn.__name__}: {time.perf_counter()-t:.4f}s")
        return result
    return wrapper

# Custom context manager
@contextmanager
def managed_resource():
    r = acquire()
    try:
        yield r
    finally:
        release(r)
arbindbuilds.com/cheatsheets/python-developer-cheatsheet
← Back to Cheatsheets