Python Standard Library Essentials

Use the most useful standard library modules for system access, paths, counting and grouping, and quick statistics.

Lesson 55 of 107Intermediate13 min read

The Python standard library is the large collection of modules that ships with every Python installation, so you can import them without installing anything. Before writing a helper or adding a third-party package, it's worth checking whether the standard library already solves the problem:

Python
from collections import Counter
from statistics import mean
print(Counter(["pear", "apple", "pear"]).most_common(1))   # [('pear', 2)]
print(mean([8, 12, 10]))                                   # 10

This lesson tours four areas you'll use constantly: os and sys for the running process and the operating system, pathlib for files and folders, collections for specialised containers, and statistics for quick numeric summaries. A table at the end points to other modules worth knowing. The examples come from an orchard recording its harvest.

os and sys

os talks to the operating system; sys talks to the Python interpreter itself.

Python
import os, sys
print(os.getenv("HARVEST_SEASON", "autumn"))  # an environment variable, with a default
print(os.cpu_count())                          # CPU cores on this machine
print(sys.version_info[:2])                    # e.g. (3, 13)
print(sys.argv)                                # command-line arguments
print(sys.platform)                            # 'linux', 'win32', 'darwin'

Useful pieces of os: os.environ and os.getenv() for environment variables, os.getcwd() for the current folder, and os.replace() for atomic file renames. Useful pieces of sys: sys.argv for command-line arguments, sys.exit(code) to stop with an exit status, sys.stdin/sys.stdout/sys.stderr for streams, and sys.path for where imports are searched.

Keep the two concerns apart: settings for this run (arguments, environment variables) versus facts about the machine or interpreter (platform, version). Environment handling is covered in detail in environment variables and configuration.

pathlib

pathlib.Path represents file-system paths as objects and replaces most of the older os.path functions:

Python
from pathlib import Path
data = Path("harvest") / "2026" / "yields.csv"
print(data.name, data.suffix, data.parent)     # yields.csv .csv harvest/2026
print(Path.home(), Path.cwd())

A relative path such as Path("harvest") is resolved against the current working directory, the folder the program was started from, which isn't necessarily the folder containing your script. For files that sit next to your code, build paths from the script's location: Path(__file__).parent / "harvest". The directory operations lesson covers creating, listing and deleting with pathlib.

collections

The collections module adds containers for common patterns:

Python
from collections import Counter, defaultdict, deque, namedtuple

picks = ["pear", "apple", "pear", "plum", "pear"]
counts = Counter(picks)
print(counts.most_common(2))            # [('pear', 3), ('apple', 1)]

by_row = defaultdict(list)
by_row["north"].append("pear")          # no KeyError: starts with []
print(dict(by_row))

recent = deque(maxlen=3)
for weight in [12, 15, 9, 14]:
    recent.append(weight)
print(recent)                           # deque([15, 9, 14], maxlen=3)

Tree = namedtuple("Tree", "row variety")
print(Tree("north", "pear").variety)
  • Counter counts hashable items and supports most_common(), + and -.
  • defaultdict(factory) creates a default value for a missing key on first access. Just reading d[key] inserts that default, so use key in d to test membership without side effects.
  • deque adds and removes at both ends quickly; with maxlen it keeps only the latest items.
  • namedtuple creates lightweight tuples with named fields; dataclasses are the more flexible modern alternative.

statistics

The statistics module calculates common summaries without NumPy:

Python
import statistics as st
weights = [12, 15, 9, 14, 15]
print(st.mean(weights), st.median(weights), st.mode(weights))   # 13 14 15
print(round(st.stdev(weights), 2), round(st.pstdev(weights), 2))  # 2.55 2.28

stdev() is the sample standard deviation (dividing by n − 1), appropriate when your data is a sample from a larger population. pstdev() is the population standard deviation (dividing by n), for when you have every value. Mixing them up gives slightly different numbers, which matters in reports.

The module also offers quantiles(), variance(), correlation() and linear_regression() (Python 3.10+). For large datasets or many columns, NumPy and pandas are faster; for a few hundred values in a script, statistics is perfectly adequate and needs no installation.

itertools and functools

Two more modules repay early study because they replace whole loops:

Python
from itertools import groupby, combinations, islice, chain
from functools import reduce, lru_cache

rows = ["north", "north", "south"]
print([(k, len(list(g))) for k, g in groupby(rows)])   # [('north', 2), ('south', 1)]
print(list(combinations(["pear", "plum", "fig"], 2)))  # every pair
print(list(chain([1, 2], [3])), list(islice(range(100), 3)))   # [1, 2, 3] [0, 1, 2]
  • groupby groups consecutive equal items, so sort by the same key first.
  • combinations, permutations and product generate arrangements without nested loops.
  • islice takes part of any iterator, including endless ones.
  • functools.lru_cache remembers function results, and functools.partial fixes some arguments of a function in advance.

These tools return lazy iterators, so wrap them in list() when you need to see or reuse the results.

Independent practice and a worked check

Task: build a harvest summary using a path, a variety counter, a numeric statistic and a process setting.

Python
import os
from collections import Counter
from pathlib import Path
from statistics import median

varieties = ["pear", "apple", "pear", "plum"]
weights = [12, 9, 15, 7]
out_dir = Path(os.getenv("REPORT_DIR", "reports"))

print("Most common:", Counter(varieties).most_common(1)[0][0])
print("Median weight:", median(weights))
print("Output folder:", out_dir)

This prints Most common: pear, Median weight: 10.5 and Output folder: reports when REPORT_DIR isn't set. For the worked check, the standard library type that counts repeated values is Counter.

Reference and next practice

The Python Standard Library documentation indexes every module, with dedicated pages for collections and statistics. Continue with environment configuration and pip and virtual environments. Practise with the Python exercises and Python quiz.

Standard Library Essentials Summary

  • os and sys: os provides operating system interfaces while sys describes the interpreter and its process context.
  • pathlib: Path offers object oriented path construction and filesystem operations.
  • collections: Counter counts values, defaultdict supplies missing defaults and deque supports efficient end operations.
  • statistics: mean, median and standard deviation summarize numeric observations.

Standard Library Essentials Examples

Each example shows the code, the output it produces and what each part does.

Example 1

Standard Library Essentials in a small program

Python
from collections import Counter
from statistics import mean
varieties = ["pear", "apple", "pear"]
print(dict(Counter(varieties)))
print(mean([8, 12, 10]))
Output
{'pear': 2, 'apple': 1}
10
Line-by-line explanation
  1. Line 4Counter counts each variety; dict() shows the counts as a normal dictionary.
  2. Line 5mean() returns 10 for these three weights; with whole-number data whose mean is whole, the result is an int.
Example 2

A harvest summary from several modules

Python
import os
from collections import Counter, defaultdict
from pathlib import Path
from statistics import mean, median

picks = [("north", "pear", 12), ("north", "apple", 9), ("south", "pear", 15),
         ("south", "plum", 7), ("north", "pear", 14)]

season = os.getenv("HARVEST_SEASON", "autumn")
report = Path("reports") / f"{season}.txt"

varieties = Counter(variety for _, variety, _ in picks)
weights_by_row = defaultdict(list)
for row, _, kg in picks:
    weights_by_row[row].append(kg)

print("Report file:", report)
print("Varieties:", varieties.most_common())
for row, weights in sorted(weights_by_row.items()):
    print(f"{row}: total {sum(weights)} kg, mean {mean(weights):.1f}, median {median(weights)}")
Output
Report file: reports/autumn.txt
Varieties: [('pear', 3), ('apple', 1), ('plum', 1)]
north: total 35 kg, mean 11.7, median 12
south: total 22 kg, mean 11.0, median 11.0
Line-by-line explanation
  1. Line 9The season comes from an environment variable, falling back to "autumn".
  2. Line 12Counter accepts a generator expression of varieties.
  3. Lines 13 to 15defaultdict(list) groups weights by row without checking for missing keys.
  4. Line 20The median of two values is their average, so south's is 11.0.

Common Standard Library Essentials Mistakes

Testing a defaultdict with a lookup

Don't
from collections import defaultdict
rows = defaultdict(list)
if rows["east"]:          # inserts "east": [] as a side effect
    print("east has trees")
print(dict(rows))         # {'east': []}
Do
if "east" in rows:
    print("east has trees")

Using the wrong standard deviation

Don't
from statistics import pstdev
sample = [12, 15, 9]          # three trees sampled from a large orchard
print(pstdev(sample))         # population formula underestimates the spread
Do
from statistics import stdev
print(stdev([12, 15, 9]))     # sample formula

Standard Library Essentials in Real Projects

The standard library in practice

Command-line tools combine argparse, pathlib, logging and sys.exit(); data scripts use csv, json, collections and statistics; automation uses shutil, subprocess and datetime. Because these modules are always available, scripts that rely only on the standard library run anywhere Python is installed, which is valuable on servers where installing packages is restricted.

Other modules worth knowing early: random, math, datetime, json, csv, re, itertools, functools, logging, argparse, subprocess, tempfile, unittest, sqlite3 and urllib. The Python Module of the Week site has worked examples for most of them.

Standard Library Essentials FAQ

What is the Python standard library?

It's the set of modules distributed with Python itself, covering files, text, dates, maths, networking, testing, data formats and more. You import them directly, with no pip install.

What is the difference between a standard library module and a package from pip?

Standard library modules are part of Python and available everywhere. Packages from PyPI, such as requests, pandas or Flask, must be installed with pip, usually in a virtual environment, and listed in your project's dependencies.

When should I use Counter instead of a dictionary?

Whenever you're counting things. Counter(items) replaces a loop with d[k] = d.get(k, 0) + 1, and adds most_common(), arithmetic between counters and a zero default for missing items.

What is defaultdict used for?

Grouping and accumulating without checking for missing keys. defaultdict(list) lets you write groups[key].append(value) directly, and defaultdict(int) lets you write totals[key] += amount.

Is the statistics module accurate enough for real work?

Yes, for typical script-sized data it is exact and careful with floating-point rounding. Its limitation is speed on very large datasets; for millions of values or many columns, NumPy and pandas are better choices.

How do I find out which modules the standard library has?

Browse the "Python Standard Library" index at docs.python.org, which groups modules by topic, or run help("modules") in the interactive shell to list everything installed. sys.stdlib_module_names (Python 3.10+) holds the names of all standard library modules.

Standard Library Essentials Exercises

Answer each one and check it instantly. If you get stuck, open the hint before the answer.

Multiple choiceeasy

Which standard library type counts repeated values?

Multiple choicemedium

Which review concern is valid for standard library essentials?

Standard Library Essentials Quiz

2 questions to check what you learned.

  1. Which standard library type counts repeated values?

    • Path
    • Counter
    • Python ignores the distinction
  2. Which statement correctly describes collections?

    • Counter counts values, defaultdict supplies missing defaults and deque supports efficient end operations.
    • Only the example output matters, not the rule
    • Every operation has the same behavior