ENGIMY.IO - CHEATSHEET
PYTHON × QUICK REFERENCE
REFERENCE v3.12

Python Quick Reference

Everything you need day‑to‑day – syntax, examples, and gotchas.

Data Types

Built‑in Scalars
  • int42, -3, 0
  • float3.14, 2.0, -0.001
  • boolTrue / False
  • str'hello', "world"
  • bytesb'abc'
  • Nonenull value
Containers
  • list[1, 2, 3] mutable
  • tuple(1, 2, 3) immutable
  • dict{'a': 1, 'b': 2} mutable
  • set{1, 2, 3} unique
  • frozensetfrozenset({1,2,3}) immutable
  • rangerange(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

@timer
def slow_function():
    time.sleep(1)

Common Operations

Strings
  • s.upper() / s.lower()
  • s.strip() – remove whitespace
  • s.split(',') → list
  • ','.join(list) → string
  • s.startswith('x') / .endswith('x')
  • s.replace('old','new')
  • f"value = {x}" – f‑strings
Lists
  • lst.append(x) – add to end
  • lst.insert(i, x) – insert at index
  • lst.pop(i) – remove at index (default last)
  • lst.remove(x) – remove first occurrence
  • lst.sort() / sorted(lst)
  • lst.reverse() / reversed(lst)
  • x in lst – membership
Dictionaries
  • d.get(key, default) – safe get
  • d.setdefault(key, default)
  • d.keys() / d.values() / d.items()
  • d.pop(key) – remove and return
  • d.update(other_dict) – merge
  • {**d1, **d2} – merge (Python 3.5+)
Sets
  • s.add(x) / s.remove(x)
  • s.union(t) or s | t
  • s.intersection(t) or s & t
  • s.difference(t) or s - t
  • s.symmetric_difference(t) or s ^ 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 system
  • import sys – runtime args
  • import json – JSON handling
  • import re – regex
  • import random – random numbers
  • import datetime – dates & times
  • import math – math utilities
  • import itertools – iterators
  • import collections – Counter, defaultdict, deque
Data Science / Web
  • import numpy as np
  • import pandas as pd
  • import matplotlib.pyplot as plt
  • import requests – HTTP
  • from flask import Flask – web framework
  • import 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 .venv then source .venv/bin/activate
📌 Quick Reference
Check your Python version: python --version
Run a script: python script.py
Interactive shell: python or ipython
Install package: pip install package_name
← Back to All Cheatsheets