The standard library
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.
random
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
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 valuesdatetime
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 formatCommon 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
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
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 anythinggroupby groups consecutive items with the same key (sort first). These tools are fast and save many nested loops.
Working with the system
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 codeFor paths and reading/writing files, prefer pathlib (Reading and writing files).
re: regular expressions
Regular expressions are a mini-language for patterns in text:
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.
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).
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),
]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),
]
minutes = [m for _, _, m in workouts]
activities = [a for _, a, _ in workouts]
# 1. Statistics
print(f"Mean {statistics.mean(minutes):.1f}, median {statistics.median(minutes):.1f}, "
f"stdev {statistics.stdev(minutes):.1f}")
# 2. Most common activity
activity, count = Counter(activities).most_common(1)[0]
print("Most common:", activity, count)
# 3. Dates
last = date.fromisoformat(workouts[-1][0])
print("Next check-in:", (last + timedelta(days=5)).strftime("%a %d %b %Y"))
print("Days to New Year:", (date(2027, 1, 1) - date(2026, 12, 4)).days)
# 4. Pairs of activities
print(list(combinations(sorted(set(activities)), 2)))
# 5. Random suggestion
random.seed(1)
print("Try:", random.choice(sorted(set(activities))))Summary
- The standard library ships with Python — no installation needed; check it before reaching for a package.
random,statisticsandmathcover chance and numbers;datetimehandles dates, times and durations.collectionsadds Counter, defaultdict and deque;itertoolsadds powerful looping tools.os,shutil,pathlibandsyswork with the system and files;rehandles regular expressions.- The docs at docs.python.org/3/library list every module, with examples.