Himanshu SharmaSoftware engineer
Let’s talk

Python Tutorial · Lesson 50 of 70

A tour of the Python standard library

Meet the most useful modules that ship with Python, math, random, statistics, collections, datetime, json and os.path, with short runnable examples.

14 minModules and packagesUpdated 14 November 2026

Awaiting technical review. This lesson is readable but not yet listed in search engines.

By the end of this lessonUse a handful of the most helpful standard library modules, and know how to find out what else is available.

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.

python
import math

print(math.sqrt(144))
print(math.ceil(4.2), math.floor(4.8))
print(round(math.pi, 4))
print(math.factorial(5))
result
12.0
5 4
3.1416
120

ceil 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.

python
import statistics

marks = [70, 85, 90, 85, 60]
print(statistics.mean(marks))
print(statistics.median(marks))
print(statistics.mode(marks))
result
78
85
85

random

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.

python
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)
result
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.

python
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))
result
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:

python
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())
result
2026-11-14
14 November 2026
2026-12-14
41
5

The 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.

python
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])
result
{"id": 7, "items": ["tea", "milk"], "paid": true}
<class 'str'>
tea

Notice 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.

python
import os.path

path = os.path.join("reports", "2026", "sales.csv")
print(path)
print(os.path.basename(path))
print(os.path.splitext(path))
result
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:

python
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.

python
import math

print([name for name in dir(math) if name.startswith("log")])
print(math.hypot(3, 4))
result
['log', 'log10', 'log1p', 'log2']
5.0

The 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:

  • pathlib and os for files and folders.
  • csv for spreadsheet-style data and sqlite3 for a small built-in database.
  • re for pattern matching in text.
  • time and datetime for clocks and dates.
  • argparse for command-line options.
  • unittest for writing tests.
  • itertools and functools for advanced iteration and function tools.
  • urllib for basic web requests.

One more helpful example is itertools, which can generate combinations without any loops of your own:

python
from itertools import combinations

toppings = ["cheese", "olives", "corn"]
for pair in combinations(toppings, 2):
    print(pair)
result
('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 random for security. Use secrets for passwords and tokens.
  • Naming your own file after a module, such as random.py or statistics.py. It hides the real one.
  • Forgetting that Counter and defaultdict come from collections, 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
python
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))
result
[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.

Check yourself

1. What does 'batteries included' mean for Python?
2. Why do examples that use random often call random.seed(...)?
3. Which module counts how many times each item appears?
4. Which function shows the names inside a module?