Skip to content
Kuza Ndoto Academy

The Standard Library

Beginner → IntermediateChapter 6 · Page 32 of 564 min readUpdated 15 Nov 2026

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:

ModuleWhat it's forExample
mathMathematical functions and constantsmath.sqrt(16)
randomRandom numbers and choices (games, simulations)random.choice(names)
statisticsMean, median, mode, standard deviationstatistics.median(marks)
datetimeDates, times and durationsdate(2026, 3, 14)
os and pathlibFiles, folders and pathsPath("data") / "sales.csv"
sysInformation about the running Pythonsys.version
json and csvReading and writing data filesjson.load(file)
collectionsExtra container typesCounter(votes)
itertoolsTools for looping and combiningcombinations(players, 2)
reRegular expressions (text patterns)re.findall(r"\d+", text)
timePauses and timingtime.sleep(1)
secretsSecure random values for passwords and tokenssecrets.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
Counter({'Amina': 3, 'Brian': 2, 'Chebet': 1}) [('Amina', 3)] 1 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))
{'Form 3': ['Achieng', 'Musa'], 'Form 4': ['Kiprono']}

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)
-1.29 36.82 Point(lat=-1.29, lon=36.82)

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)
march.txt march .txt 2026

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
C:\Users\Amina\projects 3 win32

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)
[('Gor Mahia', 'AFC Leopards'), ('Gor Mahia', 'Tusker'), ('AFC Leopards', 'Tusker')] 6

string, random and secrets

The string module stores handy groups of characters:

import string

print(string.ascii_uppercase)
print(string.digits)
ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789

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
['Hassan', 'Wanjiru'] 9f2c41ab07d3e856
Warning

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.

Tip

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.
  • collections gives you Counter, defaultdict and namedtuple.
  • pathlib builds file paths that work on every operating system.
  • Use random for games and secrets for anything security-related.
Up next · Modules & Packagespip & Virtual EnvironmentsInstall packages and keep projects separate.
→

Tip: use the ← and → keys to move between pages.