The Standard Library
Python comes with a huge collection of ready-made modules called the standard library. People describe Python as "batteries included" because you can work with files, dates, maths, data formats and much more before installing anything extra.
Why use the standard library?
Standard library modules are installed with Python, tested by thousands of developers and documented at docs.python.org. Before writing a tool yourself, or installing a package, it's worth checking whether the standard library already does the job. Here are some of the modules you'll use most often:
| Module | What it's for | Example |
|---|---|---|
math | Mathematical functions and constants | math.sqrt(16) |
random | Random numbers and choices (games, simulations) | random.choice(names) |
statistics | Mean, median, mode, standard deviation | statistics.median(marks) |
datetime | Dates, times and durations | date(2026, 3, 14) |
os and pathlib | Files, folders and paths | Path("data") / "sales.csv" |
sys | Information about the running Python | sys.version |
json and csv | Reading and writing data files | json.load(file) |
collections | Extra container types | Counter(votes) |
itertools | Tools for looping and combining | combinations(players, 2) |
re | Regular expressions (text patterns) | re.findall(r"\d+", text) |
time | Pauses and timing | time.sleep(1) |
secrets | Secure random values for passwords and tokens | secrets.token_hex(8) |
collections: smarter containers
Counter
A Counter counts how many times each item appears. It's perfect for tallying votes, survey answers or words in a text.
from collections import Counter votes = ["Amina", "Brian", "Amina", "Chebet", "Amina", "Brian"] tally = Counter(votes) print(tally) print(tally.most_common(1)) print(tally["Chebet"]) print(tally["Daudi"]) # missing items count as 0
defaultdict
A defaultdict creates a starting value automatically the first time you use a new key, so you don't need to check whether the key exists.
from collections import defaultdict
students = [("Form 3", "Achieng"), ("Form 4", "Kiprono"), ("Form 3", "Musa")]
by_form = defaultdict(list)
for form, name in students:
by_form[form].append(name)
print(dict(by_form))
namedtuple
A namedtuple is a tuple whose positions also have names, which makes code easier to read.
from collections import namedtuple
Point = namedtuple("Point", ["lat", "lon"])
nairobi = Point(-1.29, 36.82)
print(nairobi.lat, nairobi.lon)
print(nairobi)
pathlib, os and sys: files and the system
pathlib is the modern way to build file paths. The / operator joins parts of a path, and Python uses the correct separator for your operating system.
from pathlib import Path
report = Path("reports") / "2026" / "march.txt"
print(report.name)
print(report.stem)
print(report.suffix)
print(report.parent.name)
If you print report itself, Windows shows reports\2026\march.txt while macOS and Linux show reports/2026/march.txt. Your code stays the same on every system.
os and sys tell you about the computer and the running interpreter. The output depends on your machine, so yours will differ from this example from a Windows laptop:
import os import sys print(os.getcwd()) # current working folder print(sys.version_info.major) # major Python version print(sys.platform) # operating system
itertools: combining and looping
itertools has fast tools for common looping jobs. For example, combinations() lists every pair from a group, which is useful for drawing up fixtures.
from itertools import combinations, permutations teams = ["Gor Mahia", "AFC Leopards", "Tusker"] print(list(combinations(teams, 2))) # order doesn't matter print(len(list(permutations(teams, 2)))) # order matters (home and away)
string, random and secrets
The string module stores handy groups of characters:
import string print(string.ascii_uppercase) print(string.digits)
random is great for games, but its numbers are predictable to an attacker. For passwords, PINs and login tokens, use secrets, which is designed for security. The output is random, so yours will differ:
import random import secrets names = ["Wanjiru", "Otieno", "Nasimiyu", "Hassan"] print(random.sample(names, 2)) # two different winners for a raffle print(secrets.token_hex(8)) # 16 hex characters for a reset code
Never use random to generate passwords, one-time codes or anything security-related. Use the secrets module instead.
Where to go next
Several standard library modules have their own pages in this series: json and csv in Working with CSV & JSON, re in Regular Expressions and datetime in Dates & Times. When the standard library isn't enough, you can install third-party packages with pip.
In the interactive shell, type import collections then help(collections.Counter) to read the documentation without leaving your terminal. Press q to exit the help screen.
Key points
- The standard library ships with Python, so there's nothing extra to install.
collectionsgives youCounter,defaultdictandnamedtuple.pathlibbuilds file paths that work on every operating system.- Use
randomfor games andsecretsfor anything security-related.
Tip: use the ← and → keys to move between pages.
