The standard library

Topic 2 of 3 in Modules and packages6 min readBeginnerFree course

Overview

Python is famous for being “batteries included”: every installation comes with the standard library, over 200 modules for common jobs. Before you search for a package to install — or write something yourself — check whether the standard library already does it. This lesson is a guided tour of the modules you’ll use most.

Batteries included: a tour of the standard library. math — sqrt, pi, floor, ceil. random — choice, randint, shuffle. statistics — mean, median, stdev. datetime — dates, times, timedelta. pathlib — paths and files. os and shutil — environment, copy, move. json and csv — data formats. collections — Counter, defaultdict, deque. itertools — combinations, groupby. re — regular expressions. argparse — command-line options. logging — diagnostic messages. urllib.request — fetch from the web. sqlite3 — a built-in database. unittest — testing. No installation needed — these ship with every Python. Full list: docs.python.org/3/library.

random

Python
import random

random.randint(1, 6)                 # a dice roll: 1 to 6 inclusive
random.random()                      # a float from 0.0 up to (not including) 1.0
random.choice(["rock", "paper", "scissors"])
random.sample(range(1, 50), 6)       # 6 different numbers
cards = list(range(10))
random.shuffle(cards)                # shuffles in place
random.seed(42)                      # make the sequence repeatable (for tests)

random is for games and simulations. For passwords and security tokens, use the secrets module (secrets.token_urlsafe()), which is designed to be unpredictable.

statistics

Python
import statistics

data = [30, 45, 25, 60, 35, 40]
statistics.mean(data)        # 39.1666…
statistics.median(data)      # 37.5
statistics.mode([1, 2, 2])   # 2
statistics.stdev(data)       # spread of the values

datetime

Python
from datetime import date, datetime, timedelta

today = date.today()
deadline = date(2026, 12, 24)
(deadline - date(2026, 12, 4)).days       # 20 — subtracting dates gives a timedelta
date(2026, 12, 4) + timedelta(weeks=2)    # date(2026, 12, 18)

now = datetime.now()
now.strftime("%d/%m/%Y %H:%M")            # format: '04/12/2026 14:30'
datetime.strptime("2026-12-04", "%Y-%m-%d")   # parse text into a datetime
date.fromisoformat("2026-12-04")          # parse the standard ISO format

Common format codes: %Y year, %m month number, %d day, %B month name, %b short month, %A weekday, %a short weekday, %H:%M time. For time zones, use zoneinfo: datetime.now(ZoneInfo("Asia/Kolkata")).

collections

Python
from collections import Counter, defaultdict, deque

Counter("mississippi").most_common(2)     # [('i', 4), ('s', 4)]
Counter(["run", "swim", "run"])           # Counter({'run': 2, 'swim': 1})

groups = defaultdict(list)                # missing keys start as []
groups["red"].append("Asha")              # no setdefault needed

recent = deque(maxlen=3)                  # keeps only the last 3 items
for page in ["home", "shop", "cart", "pay"]:
    recent.append(page)                   # deque(['shop', 'cart', 'pay'])

Counter replaces the counting loop from Dictionaries with one line.

itertools

Python
from itertools import combinations, permutations, product, chain, groupby, islice

list(combinations("ABC", 2))      # [('A', 'B'), ('A', 'C'), ('B', 'C')]
list(permutations("AB"))          # [('A', 'B'), ('B', 'A')]
list(product([1, 2], "xy"))       # [(1, 'x'), (1, 'y'), (2, 'x'), (2, 'y')]
list(chain([1, 2], [3]))          # [1, 2, 3]
list(islice(range(100), 3))       # [0, 1, 2] — the first n of anything

groupby groups consecutive items with the same key (sort first). These tools are fast and save many nested loops.

Working with the system

Python
import os, shutil, sys

os.getcwd()                         # current working directory
os.environ.get("HOME")              # environment variables
shutil.copy("a.txt", "backup/")     # copy a file
shutil.move("old.txt", "new.txt")   # move or rename
shutil.rmtree("build")              # delete a folder and everything in it — careful!
sys.argv                            # command-line arguments (see "Command-line programs")
sys.exit(1)                         # stop with an exit code

For paths and reading/writing files, prefer pathlib (Reading and writing files).

re: regular expressions

Regular expressions are a mini-language for patterns in text:

Python
import re

re.findall(r"\d+", "Order 12, then 7 more")            # ['12', '7']
re.search(r"[\w.]+@[\w.]+", "mail asha@example.com").group()   # 'asha@example.com'
re.sub(r"\s+", " ", "too    many   spaces")            # 'too many spaces'

They’re powerful but hard to read; for simple jobs, string methods are clearer.

And more

Module For
json, csv data files (CSV and JSON)
argparse command-line options (Command-line programs)
logging messages with levels and timestamps (Debugging)
sqlite3 a full SQL database in a single file
urllib.request downloading from the web (the third-party requests package is friendlier)
unittest testing (pytest is more popular — Testing with pytest)
zipfile, tarfile archives
time time.sleep(2), measuring durations with time.perf_counter()
copy copy.deepcopy for nested data
decimal, fractions exact money and fractions

Finding what you need

  • The official list: docs.python.org/3/library — each module has a page with examples.
  • In the REPL: import datetime; help(datetime.timedelta).
  • Search “python standard library” plus the task (“python standard library zip files”).

Habit: before installing a package or writing a utility, spend a minute checking whether the standard library already has it. It usually does.

Exercise

A weekly fitness report

Use only the standard library. Given a week of workouts, print: (1) the mean, median and standard deviation (1 decimal place) of the minutes using statistics; (2) the most common activity and its count using collections.Counter; (3) the date of the last workout plus 5 days, formatted like Wed 09 Dec 2026, and how many days from 4 December 2026 until 1 January 2027 using datetime; (4) every pair of activities you could combine, using itertools.combinations on the sorted unique activities; (5) a random workout chosen with random.choice after random.seed(1) (any output is fine).

Python
import random
import statistics
from collections import Counter
from datetime import date, timedelta
from itertools import combinations

workouts = [
    ("2026-11-28", "run", 30),
    ("2026-11-29", "swim", 45),
    ("2026-11-30", "run", 25),
    ("2026-12-01", "yoga", 60),
    ("2026-12-02", "run", 35),
    ("2026-12-04", "swim", 40),
]

Summary

  • The standard library ships with Python — no installation needed; check it before reaching for a package.
  • random, statistics and math cover chance and numbers; datetime handles dates, times and durations.
  • collections adds Counter, defaultdict and deque; itertools adds powerful looping tools.
  • os, shutil, pathlib and sys work with the system and files; re handles regular expressions.
  • The docs at docs.python.org/3/library list every module, with examples.