Standard Library Highlights

Difficulty: Intermediate

Python's standard library is one of its greatest strengths, often described as 'batteries included.' It ships with hundreds of modules covering everything from file handling to networking to data compression. Mastering the key standard library modules dramatically increases your productivity because you can solve common problems without installing third-party packages. In interviews, knowledge of the standard library signals that you are an experienced Python developer.

The os module provides functions for interacting with the operating system: os.getcwd() returns the current working directory, os.listdir() lists files, os.makedirs() creates nested directories, os.environ accesses environment variables, and os.path handles path manipulation. The sys module gives access to Python interpreter internals: sys.argv holds command-line arguments, sys.path lists module search paths, sys.exit() terminates the program, and sys.stdin/stdout/stderr provide access to standard I/O streams.

The math module offers mathematical functions and constants: sqrt(), pow(), log(), sin(), cos(), ceil(), floor(), factorial(), gcd(), and constants pi and e. For random number generation, the random module provides random.random() for a float between 0 and 1, random.randint(a, b) for an integer in [a, b], random.choice() to pick from a sequence, random.shuffle() to reorder a list in place, and random.sample() for random sampling without replacement.

The datetime module handles dates and times. datetime.datetime.now() gets the current timestamp, datetime.date.today() gets today's date, timedelta represents a duration for date arithmetic, and strftime()/strptime() handle formatting and parsing. Date arithmetic is intuitive: you can subtract two dates to get a timedelta, or add a timedelta to a date to get a future date.

The itertools module provides memory-efficient iterator building blocks. Key functions include chain() (concatenate iterables), combinations() and permutations() (combinatorics), product() (Cartesian product), groupby() (group consecutive elements), count() (infinite counter), cycle() (infinite repeater), and islice() (slice an iterator). The functools module offers higher-order function utilities: reduce() applies a function cumulatively, lru_cache decorates a function for memoization, partial() creates a new function with some arguments pre-filled, and wraps() preserves metadata when writing decorators.

Code examples

os and sys Essentials

import os
import sys

# os.path operations
print(os.path.join("data", "files", "report.csv"))
print(os.path.splitext("image.png"))

# sys module
print(f"Python version: {sys.version_info.major}.{sys.version_info.minor}")
print(f"Platform: {sys.platform}")
print(f"Max integer size: {sys.maxsize}")

os.path works with file paths as strings. sys provides runtime information about the Python interpreter. In Pyodide, sys.platform reports 'emscripten' since it runs in WebAssembly.

datetime Arithmetic

from datetime import datetime, date, timedelta

# Create specific dates
start = date(2025, 1, 1)
end = date(2025, 12, 31)

# Date arithmetic
delta = end - start
print(f"Days in 2025: {delta.days}")

# Add days to a date
future = start + timedelta(days=90)
print(f"90 days from Jan 1: {future}")

# Format dates
dt = datetime(2025, 6, 15, 14, 30)
print(dt.strftime("%B %d, %Y at %I:%M %p"))

Subtracting two dates produces a timedelta object. Adding a timedelta to a date produces a new date. strftime() formats dates using format codes: %B for full month name, %d for day, %Y for year, %I for 12-hour clock, %p for AM/PM.

itertools Combinatorics

from itertools import combinations, permutations, chain, product

# combinations: order doesn't matter
print(list(combinations("ABC", 2)))

# permutations: order matters
print(list(permutations("AB", 2)))

# chain: concatenate iterables
print(list(chain([1, 2], [3, 4], [5])))

# product: Cartesian product
print(list(product("AB", "12")))

combinations picks r items without regard to order. permutations considers order, so ('A','B') and ('B','A') are distinct. chain flattens multiple iterables into one. product generates all pairs from two iterables.

functools: reduce and lru_cache

from functools import reduce, lru_cache

# reduce applies a function cumulatively
numbers = [1, 2, 3, 4, 5]
total = reduce(lambda a, b: a + b, numbers)
print(f"Sum via reduce: {total}")

product_val = reduce(lambda a, b: a * b, numbers)
print(f"Product via reduce: {product_val}")

# lru_cache for memoization
@lru_cache(maxsize=None)
def fibonacci(n):
    if n < 2:
        return n
    return fibonacci(n - 1) + fibonacci(n - 2)

print(f"fib(10) = {fibonacci(10)}")
print(f"fib(30) = {fibonacci(30)}")

reduce() folds a sequence using a binary function: ((((1+2)+3)+4)+5) = 15. lru_cache memoizes function results, making the naive recursive fibonacci O(n) instead of O(2^n). Without caching, fib(30) would take billions of calls.

Key points

Concepts covered

os Module, sys Module, math Module, random Module, datetime Module, itertools, functools