4 snippets

Python Snippets

Pythonic code snippets and common patterns.

lists

List comprehension patterns

Pythonic ways to create and transform lists.

# Basic comprehension
squares = [x**2 for x in range(10)]

# With condition
evens = [x for x in range(20) if x % 2 == 0]

# Nested comprehension (flatten)
flat = [x for row in matrix for x in row]

# Dict comprehension
word_lengths = {w: len(w) for w in words}

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

dictionaries

Merge dictionaries

Multiple ways to merge dicts in Python.

# Python 3.9+ (cleanest)
merged = dict_a | dict_b

# Update in place
dict_a |= dict_b

# Python 3.5+ (spread)
merged = {**dict_a, **dict_b}

# Older Python
merged = dict_a.copy()
merged.update(dict_b)

files

Read and write files

Common file operations with context managers.

# Read entire file
with open('file.txt', 'r') as f:
    content = f.read()

# Read lines
with open('file.txt') as f:
    lines = f.readlines()

# Write file
with open('output.txt', 'w') as f:
    f.write('Hello, world!')

# Read JSON
import json
with open('data.json') as f:
    data = json.load(f)

# Write JSON
with open('output.json', 'w') as f:
    json.dump(data, f, indent=2)

strings

String formatting

Modern f-strings and formatting techniques.

name, age = "Alice", 30

# f-string (recommended)
msg = f"Hello, {name}! You are {age}."

# f-string with expressions
msg = f"Next year: {age + 1}"
msg = f"Upper: {name.upper()}"

# Number formatting
f"{1234567:,}"        # '1,234,567'
f"{3.14159:.2f}"      # '3.14'
f"{0.856:.1%}"        # '85.6%'
f"{42:08b}"           # '00101010' (binary)

# Padding
f"{'hi':>10}"         # '        hi'  (right-align)
f"{'hi':<10}"         # 'hi        '  (left-align)
f"{'hi':^10}"         # '    hi    '  (center)
All Languages