The Standard Library
Discover Python's built-in treasure chest of ready-to-use modules — math, random, datetime, and more — so you can do powerful things without installing anything.
When you install Python, you don't just get the language itself — you get a huge collection of pre-built tools called the standard library. Think of it like a well-stocked kitchen: pots, pans, knives, and spices are already there. You don't need to go shopping before you can cook.
This philosophy even has a name: "batteries included". Python comes with modules for math, random numbers, dates and times, file paths, working with JSON data, and much more. Before you search for a third-party package, always check whether Python already ships what you need.
See it in action
— step through the idea, then dive into the details below.Python Comes Pre-Stocked
Python ships with a massive built-in toolkit called the standard library — hundreds of ready-to-use modules for math, dates, files, JSON, and more. No installation needed.
The Library Analogy
Imagine a huge public library. The standard library is like the reference section — free, always available, and organised by topic. You just walk up to the shelf (write import math) and take what you need.
#Importing a Module
Every standard library module must be imported before you can use it. The import statement is the key that opens the shelf. Once imported, you access its contents with a dot: module.thing.
import math
print(math.pi) # the constant π
print(math.sqrt(16)) # square root
print(math.ceil(4.2)) # round up#random — Roll the Dice
The random module lets you generate random numbers and make random choices. Two functions you will reach for constantly: - random.randint(a, b) — a random whole number between a and b (inclusive) - random.choice(sequence) — pick one random item from a list
import random
# Random integer between 1 and 6 (like rolling a die)
die = random.randint(1, 6)
print("You rolled:", die)
# Pick a random item from a list
colors = ["red", "green", "blue"]
print("Chosen color:", random.choice(colors))#datetime — Working with Dates and Times
Handling dates manually is surprisingly tricky. The datetime module does the heavy lifting: it knows about leap years, time zones, and how to format dates nicely.
from datetime import date, datetime
today = date.today()
print("Today is:", today)
now = datetime.now()
print("Right now:", now.strftime("%H:%M on %d %B %Y"))from module import name
Instead of import datetime and then typing datetime.datetime.now(), you can write from datetime import datetime and then just datetime.now(). Use whichever style reads more clearly to you.
#os and pathlib — Navigating Files
The os module lets you interact with the operating system — list files, check if a path exists, get the current directory, and more. The newer pathlib module does similar things with an even cleaner style. Both ship with Python.
import os
# Current working directory
print(os.getcwd())
# Check if a file exists
print(os.path.exists("notes.txt")) # True or False
# List files in the current directory
files = os.listdir(".")
print(files[:3]) # show first threefrom pathlib import Path
p = Path(".")
for f in p.iterdir():
if f.suffix == ".py":
print(f.name)#json — Reading and Writing JSON
JSON is the most common format for sharing data on the internet. Python's json module converts between JSON text and Python dictionaries/lists with just two functions: - json.dumps(obj) — Python object to a JSON string - json.loads(text) — JSON string to a Python object
import json
data = {"name": "Alice", "score": 42, "tags": ["python", "beginner"]}
# Convert Python dict to JSON string
json_text = json.dumps(data, indent=2)
print(json_text)
# Convert JSON string back to Python
parsed = json.loads(json_text)
print(parsed["name"])#sys — Talking to the Python Interpreter
The sys module gives you access to Python itself: the version it is running, command-line arguments passed to your script, and the ability to exit cleanly.
import sys
print("Python version:", sys.version)
print("Platform:", sys.platform)
print("Script arguments:", sys.argv)#collections — Smarter Containers
The collections module gives you upgraded versions of Python's built-in containers. Two crowd favourites: - Counter — counts how often each item appears - defaultdict — a dictionary that never raises a KeyError because it creates a default value automatically
from collections import Counter
words = ["apple", "banana", "apple", "cherry", "banana", "apple"]
counts = Counter(words)
print(counts)
print("Most common:", counts.most_common(2))from collections import defaultdict
scores = defaultdict(list) # missing keys get an empty list
scores["Alice"].append(90)
scores["Alice"].append(88)
scores["Bob"].append(76)
print(dict(scores))Don't Re-invent the Wheel
A very common beginner mistake: writing loops to count items, shuffle lists, or manipulate file paths — all of which the standard library already does for you. Always ask "does Python already have this?" before writing it yourself. The answer is yes more often than you'd expect.
#How to Discover More Modules
The official Python documentation at docs.python.org has a full index of every standard library module. A quick way to explore is: - Search online for python stdlib <what you need> (e.g. "python stdlib compress files") - Run help('modules') in a Python REPL to list everything installed - Use dir(module) to see what a module contains after importing it
Check the stdlib Before Installing
Before reaching for pip install, spend 30 seconds checking whether the standard library already covers your need. It saves you a dependency, keeps your project lighter, and works on any machine with Python installed — no setup required.
Which standard library module would you use to pick a random item from a list?
Key takeaways
- Python ships with a huge standard library — "batteries included" means you can do a lot before installing anything extra.
- Use `import module` or `from module import name` to access any standard library module.
- Key modules to know: `math`, `random`, `datetime`, `os`/`pathlib`, `json`, `sys`, and `collections`.
- Always check the standard library before reaching for a third-party package.
- The official docs at docs.python.org are the definitive guide to everything available.
What does this code print?
import math
print(math.ceil(4.2))
print(math.sqrt(25))This code tries to convert a Python dictionary to a JSON string, but it has a bug. What is wrong?
import json
data = {"name": "Alice", "score": 42}
json_text = json.loads(data)
print(json_text)Complete the code so it imports Counter from the collections module and prints the count of each word.
from import Counter words = ["cat", "dog", "cat", "bird"] print(Counter(words))
Put these lines in the right order to import the random module and print a random choice from a list of fruits.
fruits = ["apple", "banana", "mango"]
pick = random.choice(fruits)
print("You got:", pick)import random
Write a short program that: (1) picks 5 random numbers between 1 and 100 and stores them in a list, (2) prints the list, (3) prints the minimum and maximum using the math module (or Python built-ins), and (4) prints today's date using datetime. Bonus: use Counter to check if any number was picked twice (hint: try running it several times — with only 5 picks from 1-100 duplicates are rare, but possible).
Try it live — edit the code and hit Run to execute real Python: