Cheatsheet - Python

Environment & Package Management

# Virtual environment setup
$ python3 -m venv .venv
$ source .venv/bin/activate         # Linux / macOS
$ .venv\Scripts\activate            # Windows

# Package management
$ pip install <package>
$ pip install -r requirements.txt
$ pip freeze > requirements.txt
$ pip list --outdated

Types & Conversions

# Conversions
int("42")               # 42
float("3.14")           # 3.14
str(100)                # "100"
bool(0)                 # False (0, "", [], {}, None are falsy)

# ASCII / Unicode & Base Conversion
ord('a')                # 97
chr(97)                 # 'a'
bin(14)                 # '0b1110'
hex(255)                # '0xff'
int('ff', 16)           # 255
int('1110', 2)          # 14
bytes.fromhex('4142')   # b'AB'
b'AB'.hex()             # '4142'

Strings & Formatting

s = "  Hello, World!  "
s.strip()               # "Hello, World!"
s.lower()               # "  hello, world!  "
s.replace("World", "Python")
"a,b,c".split(",")      # ['a', 'b', 'c']
",".join(['a', 'b'])    # "a,b"
s.startswith("  He")    # True
"cat" in "scatter"      # True

# Slicing: [start:stop:step]
s = "Python"
s[0:2]                  # "Py"
s[::-1]                 # "nohtyP" (reverse)

# Modern F-Strings (Python 3.6+)
name, pi = "Ada", 3.14159
f"Name: {name}, Pi: {pi:.2f}"   # "Name: Ada, Pi: 3.14"
f"{255:#x}, {255:08b}"          # "0xff, 00001111"
f"{1000000:_}"                  # "1_000_000"
f"{name=}"                      # "name='Ada'" (debugging)

Lists

nums = [1, 2, 3]
nums.append(4)                  # [1, 2, 3, 4]
nums.extend([5, 6])             # [1, 2, 3, 4, 5, 6]
nums.insert(0, 99)              # Insert 99 at index 0
val = nums.pop()                # Removes & returns last item
nums.remove(99)                 # Removes first occurrence of 99
nums.index(3)                   # Returns index of 3 (ValueError if absent)

# 2D Grid initialization (Avoid [[0]*m]*n due to shared references)
grid = [[0] * 3 for _ in range(4)]   # 4 rows x 3 columns of independent lists

# Unpacking
first, *middle, last = [1, 2, 3, 4, 5]  # first=1, middle=[2,3,4], last=5

# Comprehensions & Sorting
squares = [x**2 for x in range(5) if x % 2 == 0] # [0, 4, 16]
sorted_desc = sorted(nums, reverse=True)
nums.sort(key=lambda x: abs(x))                  # In-place sort

Dictionaries & Sets

# Dict operations
d = {"a": 1, "b": 2}
d.get("c", 0)           # 0 (fallback default)
d.setdefault("c", 3)    # Sets "c": 3 if absent
d.keys(), d.values(), d.items()

# Dict merge (Python 3.9+)
merged = {"a": 1} | {"b": 2, "a": 9}  # {'a': 9, 'b': 2}
inverted = {v: k for k, v in d.items()}

# Sets (Unique items, O(1) lookups)
s1 = {1, 2, 3}
s2 = {3, 4, 5}
s1 | s2                 # Union: {1, 2, 3, 4, 5}
s1 & s2                 # Intersection: {3}
s1 - s2                 # Difference: {1, 2}
s1 ^ s2                 # Symmetric difference: {1, 2, 4, 5}

Control Flow & Pattern Matching

# Ternary operator
status = "Adult" if age >= 18 else "Minor"

# Walrus operator (Python 3.8+)
if (n := len(nums)) > 3:
    print(f"List has {n} items")

# Structural Pattern Matching (Python 3.10+)
match command.split():
    case ["quit" | "exit"]:
        exit()
    case ["go", direction]:
        move(direction)
    case ["set", key, value]:
        config[key] = value
    case _:
        print("Unknown command")

Functions & Lambdas

# Args, kwargs, and keyword-only arguments
def configure(host, port=8080, *tags, verbose=False, **options):
    pass

# Lambda (anonymous function)
add = lambda x, y: x + y
pairs = [(1, "b"), (2, "a")]
pairs.sort(key=lambda item: item[1])

Datetime Quick Reference

from datetime import datetime, date, timedelta, timezone

now = datetime.now()
utc_now = datetime.now(timezone.utc)
today = date.today()

# Formatting & Parsing
formatted = now.strftime("%Y-%m-%d %H:%M:%S")
parsed = datetime.strptime("2024-05-18", "%Y-%m-%d")

# Duration arithmetic
tomorrow = now + timedelta(days=1)
two_hours_ago = now - timedelta(hours=2)
Directive Description Example
%Y / %y 4-digit / 2-digit year 2024 / 24
%m / %B / %b Month (01-12) / Full month / Abbrev 05 / May / May
%d / %j Day of month (01-31) / Day of year (001-366) 18 / 139
%H / %I Hour (24-hour: 00-23) / (12-hour: 01-12) 14 / 02
%M / %S Minute (00-59) / Second (00-59) 05 / 30
%p AM or PM designation PM
%z / %Z UTC offset / Timezone name +0000 / UTC

Common Standard Library Idioms

from collections import defaultdict, Counter
import itertools

# Group frequency
counts = Counter(["apple", "banana", "apple"])     # Counter({'apple': 2, 'banana': 1})
counts.most_common(1)                              # [('apple', 2)]

# Defaultdict
grouped = defaultdict(list)
grouped["keys"].append("value")

# Itertools
for item, group in itertools.groupby(sorted([1, 1, 2, 3, 3])):
    print(item, list(group))

# Enumerate & Zip
for idx, val in enumerate(["a", "b"]):
    print(idx, val)

for a, b in zip([1, 2], ["x", "y"]):
    print(a, b)