Python Quick Reference
Everything you need day‑to‑day – syntax, examples, and gotchas.
Data Types
Built‑in Scalars
int– 42, -3, 0float– 3.14, 2.0, -0.001bool– True / Falsestr– 'hello', "world"bytes– b'abc'None– null value
Containers
list– [1, 2, 3] mutabletuple– (1, 2, 3) immutabledict– {'a': 1, 'b': 2} mutableset– {1, 2, 3} uniquefrozenset– frozenset({1,2,3}) immutablerange– range(0, 10, 2)
Type Conversion
int(3.14) # → 3 float(42) # → 42.0 str(123) # → '123' bool(0) # → False list((1,2,3)) # → [1, 2, 3] tuple([1,2,3])# → (1, 2, 3) dict([('a',1),('b',2)]) # → {'a': 1, 'b': 2} set([1,2,2]) # → {1, 2}
Control Flow
if / elif / else
if x > 0: print("positive") elif x == 0: print("zero") else: print("negative")
Loops
# for loop over iterable for i in range(5): print(i) # 0 1 2 3 4 # enumerate with index for idx, val in enumerate(['a','b','c']): print(idx, val) # while loop n = 0 while n < 3: print(n) n += 1 # break / continue / else for x in range(10): if x == 3: continue # skip 3 if x == 7: break # exit loop print(x) else: print("loop completed") # only if no break
Comprehensions
# List squares = [x**2 for x in range(10)] # [0,1,4,9,...] evens = [x for x in range(20) if x % 2 == 0] # Dict square_dict = {x: x**2 for x in range(5)} # Set unique_squares = {x**2 for x in [-2, -1, 1, 2]} # Generator (lazy) gen = (x**2 for x in range(10))
📐 Functions
Definition & Arguments
def greet(name, greeting="Hello"): return f"{greeting}, {name}!" # Positional + keyword greet("Alice") # → "Hello, Alice!" greet("Bob", greeting="Hi") # → "Hi, Bob!" # *args (tuple) / **kwargs (dict) def log(*args, **kwargs): print(args, kwargs) log(1,2,3, a=4, b=5) # (1,2,3) {'a':4, 'b':5} # Lambda square = lambda x: x**2 list(map(square, [1,2,3])) # → [1,4,9]
Decorators (syntax sugar)
def timer(func): import time def wrapper(*args, **kwargs): start = time.time() result = func(*args, **kwargs) print(f"took {time.time()-start:.3f}s") return result return wrapper def slow_function(): time.sleep(1)
Common Operations
Strings
s.upper()/s.lower()s.strip()– remove whitespaces.split(',')→ list','.join(list)→ strings.startswith('x')/.endswith('x')s.replace('old','new')f"value = {x}"– f‑strings
Lists
lst.append(x)– add to endlst.insert(i, x)– insert at indexlst.pop(i)– remove at index (default last)lst.remove(x)– remove first occurrencelst.sort()/sorted(lst)lst.reverse()/reversed(lst)x in lst– membership
Dictionaries
d.get(key, default)– safe getd.setdefault(key, default)d.keys()/d.values()/d.items()d.pop(key)– remove and returnd.update(other_dict)– merge{**d1, **d2}– merge (Python 3.5+)
Sets
s.add(x)/s.remove(x)s.union(t)ors | ts.intersection(t)ors & ts.difference(t)ors - ts.symmetric_difference(t)ors ^ t
Built‑in Functions (Highlights)
len(obj) # length type(obj) # type of object id(obj) # memory address isinstance(obj, type) # check type range(start, stop, step) map(func, iterable) filter(func, iterable) zip(iter1, iter2) # pair elements sorted(iterable, key=..., reverse=...) sum(iterable), min(iterable), max(iterable) any(iterable), all(iterable) # boolean checks enumerate(iterable) # (index, value)
File I/O
# Read with open('file.txt', 'r') as f: content = f.read() # entire file line = f.readline() # one line lines = f.readlines() # list of lines # Write (overwrite) with open('out.txt', 'w') as f: f.write("Hello\n") # Append with open('out.txt', 'a') as f: f.write("more\n")
Exception Handling
try: result = 10 / 0 except ZeroDivisionError as e: print("Error:", e) except Exception as e: print("Generic:", e) else: print("No exception") # only if no exception finally: print("Always runs")
Standard Library Gems
Essential
import os– file systemimport sys– runtime argsimport json– JSON handlingimport re– regeximport random– random numbersimport datetime– dates & timesimport math– math utilitiesimport itertools– iteratorsimport collections– Counter, defaultdict, deque
Data Science / Web
import numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport requests– HTTPfrom flask import Flask– web frameworkimport sqlite3– embedded SQL
Pythonic Tips
- Unpacking:
a, b = (1, 2)and*rest, last = [1,2,3,4] - Swap variables:
a, b = b, a - Chained comparisons:
0 < x < 10 - Truthiness: Empty containers, 0, None are
False - Context managers:
with– for files, locks, connections - Type hints (optional):
def greet(name: str) -> str: - Virtual environments:
python -m venv .venvthensource .venv/bin/activate
📌 Quick Reference
Check your Python version:
Run a script:
Interactive shell:
Install package:
python --versionRun a script:
python script.pyInteractive shell:
python or ipythonInstall package:
pip install package_name