After this lesson you can reach for the right built-in module instead of writing common code yourself, and you know how to explore modules you have never used.
What the standard library is
When you install Python you also get hundreds of ready-made modules. This collection is called the standard library, and it is one of the reasons Python is productive. No installation is needed: you just import what you want. This lesson tours the modules a beginner reaches for most often. It is a map, not a manual. You will not memorise any of it, but knowing what exists saves hours.
math
The math module holds numeric functions and constants.
import math
print(math.sqrt(144))
print(math.ceil(4.2), math.floor(4.8))
print(round(math.pi, 4))
print(math.factorial(5))12.0
5 4
3.1416
120ceil rounds up and floor rounds down, which is handy for jobs such as working out how many boxes are needed for a number of items.
statistics
For averages you do not need to write loops. The statistics module does them for you.
import statistics
marks = [70, 85, 90, 85, 60]
print(statistics.mean(marks))
print(statistics.median(marks))
print(statistics.mode(marks))78
85
85random
The random module produces pseudo-random numbers. They look random but follow a formula. Calling random.seed(...) with a fixed number makes the sequence repeat, which is useful for examples and tests.
import random
random.seed(7)
print(random.randint(1, 6))
print(random.choice(["tea", "coffee", "milk"]))
items = [1, 2, 3, 4, 5]
random.shuffle(items)
print(items)3
tea
[2, 3, 5, 1, 4]The numbers above come from running these lines on Python 3.9. Without the seed, every run would differ, and other Python versions may produce different sequences from the same seed, so never write a test that depends on specific random values unless you control the version. For passwords and tokens, never use random. Use the secrets module, which is designed to be unpredictable.
collections
collections adds specialised containers. Counter counts things, and defaultdict creates missing dictionary entries automatically.
from collections import Counter, defaultdict
sales = ["tea", "milk", "tea", "eggs", "tea", "milk"]
counts = Counter(sales)
print(counts)
print(counts.most_common(2))
by_first_letter = defaultdict(list)
for item in sales:
by_first_letter[item[0]].append(item)
print(dict(by_first_letter))Counter({'tea': 3, 'milk': 2, 'eggs': 1})
[('tea', 3), ('milk', 2)]
{'t': ['tea', 'tea', 'tea'], 'm': ['milk', 'milk'], 'e': ['eggs']}datetime
Dates and times are fiddly, so use the module built for them. Here dates are written out explicitly, so the output never changes:
from datetime import date, timedelta
opened = date(2026, 11, 14)
print(opened)
print(opened.strftime("%d %B %Y"))
print(opened + timedelta(days=30))
print((date(2026, 12, 25) - opened).days)
print(opened.weekday())2026-11-14
14 November 2026
2026-12-14
41
5The weekday() call counts Monday as 0, so the 5 means Saturday. date.today() gives the current date, so its output changes daily. The later lesson on dates and times covers this module properly.
json
json converts Python dictionaries and lists to text and back. It is the format most web services use.
import json
order = {"id": 7, "items": ["tea", "milk"], "paid": True}
text = json.dumps(order)
print(text)
print(type(text))
back = json.loads(text)
print(back["items"][0]){"id": 7, "items": ["tea", "milk"], "paid": true}
<class 'str'>
teaNotice that Python's True becomes the JSON true. Reading and writing JSON files is covered in the lesson on CSV and JSON.
os.path and sys
os.path builds and takes apart file path strings, using the right separator for the operating system.
import os.path
path = os.path.join("reports", "2026", "sales.csv")
print(path)
print(os.path.basename(path))
print(os.path.splitext(path))reports/2026/sales.csv
sales.csv
('reports/2026/sales', '.csv')The separators shown are for macOS and Linux. On Windows the joined path would use backslashes. The newer pathlib module, covered in the files lessons, is often nicer for this job.
The sys module exposes details about the running Python. The output depends on the machine, so this example is not run here:
import sys
print(sys.version)
print(sys.argv)sys.argv holds the command-line arguments given to your script.
Finding out what a module offers
You do not need to memorise any of this. Python can describe its own modules. dir lists names, and help prints documentation. Here the names starting with log are listed, followed by one of the functions in use.
import math
print([name for name in dir(math) if name.startswith("log")])
print(math.hypot(3, 4))['log', 'log10', 'log1p', 'log2']
5.0The official documentation page for each module lists everything with examples. When you face a task, search the standard library first, because a well-tested module is usually better than code you write yourself.
A few more modules to know about
The list below is far from complete, but these names are worth remembering, because you will meet them again:
pathlibandosfor files and folders.csvfor spreadsheet-style data andsqlite3for a small built-in database.refor pattern matching in text.timeanddatetimefor clocks and dates.argparsefor command-line options.unittestfor writing tests.itertoolsandfunctoolsfor advanced iteration and function tools.urllibfor basic web requests.
One more helpful example is itertools, which can generate combinations without any loops of your own:
from itertools import combinations
toppings = ["cheese", "olives", "corn"]
for pair in combinations(toppings, 2):
print(pair)('cheese', 'olives')
('cheese', 'corn')
('olives', 'corn')Each pair appears once and the order inside a pair does not matter. Without the module you would write nested loops and carefully avoid duplicates.
Common mistakes
- Reinventing something that exists. Sorting, counting, averages and dates all have standard tools.
- Using
randomfor security. Usesecretsfor passwords and tokens. - Naming your own file after a module, such as
random.pyorstatistics.py. It hides the real one. - Forgetting that
Counteranddefaultdictcome fromcollections, so they need to be imported first. - Assuming seeded random numbers are the same on every Python version.
Exercise
Using a seed of 1, simulate five dice rolls with random.randint(1, 6), store them in a list, and use statistics.mean and collections.Counter to show the average and the counts.
Show one possible answer
import random
import statistics
from collections import Counter
random.seed(1)
rolls = [random.randint(1, 6) for _ in range(5)]
print(rolls)
print(statistics.mean(rolls))
print(Counter(rolls))[2, 5, 1, 3, 1]
2.4
Counter({1: 2, 2: 1, 5: 1, 3: 1})Key points
- Python ships with a large standard library of modules. You can import them with no installation.
- math, statistics and random cover calculations, averages and (seeded) random choices.
- collections offers Counter and defaultdict. datetime handles dates and differences between them. json converts to and from text.
- os.path helps build file paths, and sys exposes details of the running Python.
- dir() and help() let you explore any module from the prompt, and the official documentation is the full reference.