Create your own
Lesson illustration

Selecting and Using Python Standard-Library Functions

Welcome back. In the previous lesson, you defined small functions with clear inputs, return values, and docstrings. This lesson extends that habit beyond code you write yourself: Python already provides many well-tested tools, and a working data scientist needs to be able to find and use them without guessing or pasting generated code.

You will learn a repeatable workflow for turning a short requirement into a documented standard-library function call. By the end, you should be able to decide whether a built-in or standard-library tool fits the job, read the official documentation for its contract, import it clearly, and verify the result with a small example.


Python’s “batteries”: built-ins, modules, and functions

Some useful tools are available immediately:

names = ["Amina", "Diego", "Mei"]

print(len(names))
print(sorted(names))
print(sum([4, 7, 9]))

print(), len(), sorted(), and sum() are built-in functions. They are part of Python’s core language environment, so they do not need an import.

Other capabilities are shipped with Python but organized into standard-library modules. A module is a file containing related code: functions, constants, and sometimes classes. Examples you will encounter often include:

NeedStandard-library moduleExample tool
Arithmetic beyond basic operatorsmathmath.log()
Basic statistical summariesstatisticsstatistics.mean()
Random sampling and simulationrandomrandom.choice()
Dates and timesdatetimedatetime.date.today()
Filename pattern matchingglobglob.glob()
CSV and JSON filescsv, jsoncsv.DictReader(), json.load()

The standard library comes with Python. You do not run pip install statistics or pip install math. Installing third-party packages and managing environments comes in the next module; for now, the important distinction is:

  • Built-in function: call it directly, such as len(values).
  • Standard-library function: import its module, then call it, such as statistics.mean(values).
  • Third-party package: install it into your environment first, then import it. Examples later include NumPy, pandas, and scikit-learn.

A period in statistics.mean is meaningful. It says: “use the name mean found inside the module named statistics.” This naming keeps related functionality grouped and makes code easier to read.

Python Documentation - How to Read and Browse the Python Docs

Watch “Python Documentation - How to Read and Browse the Python Docs” by Coding with Estefania. It shows where the official documentation is organized and how to interpret a function’s basic contract rather than treating the docs as a wall of technical text.

Watch finding the reference to see how the Python documentation leads to the Library Reference. Then watch reading a function, focusing on the function signature, its required input, and the sentence describing its returned result.


A practical workflow: requirement first, code second

Avoid beginning with “what Python function do I remember?” Start with a concise description of the job.

Suppose a stakeholder asks for the average delivery time across completed deliveries. Before writing Python, state the contract:

  • Input: a collection of numeric delivery durations, measured in minutes.
  • Output: one numeric arithmetic mean.
  • Constraints: the data should contain numeric values; an empty collection needs an explicit decision rather than silently producing a fake result.

That language points toward a statistical summary, so statistics is a sensible module to investigate. Its mean() function fits the requested operation precisely.

import statistics

delivery_minutes = [28, 31, 25, 34, 29]

typical_delivery_minutes = statistics.mean(delivery_minutes)

print(typical_delivery_minutes)

Output:

29.4

Notice the sequence:

  1. Import the module with import statistics.
  2. Store input data in a clearly named variable.
  3. Call the documented function as statistics.mean(...).
  4. Store the returned value.
  5. Inspect the result using a small example you can reason about.

The function is not called average() in Python’s statistics module. average may sound plausible, which is exactly why guessing function names is risky:

statistics.average(delivery_minutes)

That call fails because the module does not define a function with that name. Documentation converts “plausible code” into code whose behavior and name you have checked.

The documentation checklist

When you locate a possible function in the official documentation, read it as a contract. Check these five things:

  1. Location: Which module contains it?
  2. Signature: What inputs are required? Which are optional?
  3. Accepted input types: Does your value have the kind of data the function expects?
  4. Result or side effect: Does it return a new value, modify an object, print something, or write a file?
  5. Important behavior: How does it handle edge cases, such as empty data, invalid values, or an optional setting?

For example, a requirement might be: “Convert a count to a base-2 logarithmic scale.” The official standard-library tour shows math.log() with an optional base argument:

import math

log_base_two = math.log(1024, 2)

print(log_base_two)

Output:

10.0

The important point is not memorizing math.log. It is recognizing the operation, locating the likely module, then confirming how the function is called.

Optional parameters are commonly shown with square brackets in documentation, such as function(required_value[, optional_value]). A parameter written with a value, such as start=0, has a default value that Python supplies when you omit it.


Import styles and the names they create

The import form you choose changes which names are available in your code.

Prefer importing the module during early learning

import statistics

mean_duration = statistics.mean([28, 31, 25])

This creates one name in your notebook or script: statistics. The function remains clearly associated with its source module.

For the work you are doing now, this is usually the most readable choice. When you return to a notebook a week later, statistics.mean(...) explains substantially more than an unexplained mean(...).

Importing one function directly

You can also import a specific name:

from statistics import mean

mean_duration = mean([28, 31, 25])

This is valid, and it is useful when one function is repeatedly used in a focused script. But after this import, statistics itself is not available:

from statistics import mean

print(mean([28, 31, 25]))

# statistics.mean([28, 31, 25])  # NameError: statistics is not defined

The first style makes provenance visible; the second is shorter. Prefer the module-qualified style until you are comfortable tracing names through a program.

Aliases

An alias gives an imported module or function a shorter local name:

import datetime as dt

today = dt.date.today()

print(today)

Aliases are valuable when they are conventional and improve readability. dt for datetime is common. Avoid inventing cryptic abbreviations merely to make lines shorter.

Avoid wildcard imports

Do not use this in normal scripts or notebooks:

from statistics import *

It adds many names to your current workspace without showing where they came from. A name can also accidentally overwrite another name you were already using. Clear imports are especially valuable in data notebooks, where cells may be run in an unpredictable order.

6. Modules — Python 3.14.0 documentation

Read the official Python tutorial’s introduction to modules and import forms. It provides the underlying model for why import statistics gives you a module name, whereas from statistics import mean gives you the function name directly.

In Section 6, read from why modules exist through the fibo import example. Focus on the fact that import fibo creates the module name, and that functions are then accessed with dot notation. Next, in Section 6.1, read the paragraphs beginning with “There is a variant of the import statement” through the direct-import example; use direct imports as a locator. Finish with the warning about wildcard imports, beginning the wildcard warning.


Selecting a function from the standard library

The standard library is large enough that nobody memorizes all of it. Competence means searching and evaluating well.

Imagine these three mini-requirements:

RequirementAppropriate choiceWhy
Count completed orderslen(completed_orders)len() is built in; no import is needed.
Calculate the arithmetic mean of numeric orders per daystatistics.mean(daily_orders)The task is a basic statistical summary.
Find all notebook files in the current folderglob.glob("*.ipynb")The task is matching filenames against a pattern.

The glob example illustrates a useful distinction: a function can return a list even when your computer happens to have no matching files.

import glob

notebook_files = glob.glob("*.ipynb")

print(notebook_files)

A possible result is:

['function_practice.ipynb', 'documentation_practice.ipynb']

Or it may be:

[]

An empty list here is not automatically an error. It means no filenames matched the pattern in the directory where Python is running. Context determines whether that behavior is acceptable.

10. Brief Tour of the Standard Library — Python 3.14.2 ...

Use this official tour as a map of useful modules rather than as a list to memorize. The selected sections show concrete examples of file-pattern matching and numerical or statistical tools that are already available with Python.

First read Section 10.2, “File wildcards,” including the glob.glob('*.py') example, and note that the wildcard pattern is an argument while the function returns a file list. Then go to Section 10.6, “Mathematics.” Locate it immediately after the preceding context sentence, and read through the math, random, and statistics examples, stopping before Section 10.7, “Internet access.” Focus on matching each module to the kind of task it serves, not on memorizing every function shown.

Use dir() and help() as local aids, not substitutes for understanding

Once a module is imported, you can inspect the names it exposes:

import statistics

print(dir(statistics))

dir() returns many names, so it is useful for discovery but not a complete explanation of which function is appropriate.

For a quick description in your current Python environment, use help():

help(statistics.mean)

Use this sequence when you are stuck:

  1. Search the official Library Reference using the task word, such as “mean,” “date,” “file pattern,” or “JSON.”
  2. Read the relevant module page and function entry.
  3. Use help() locally if you want a quick reminder or need to check the version installed on your machine.
  4. Make a tiny call with known input.
  5. Only then use the function in your larger workflow.

The documentation version also matters occasionally. If your local Python version differs substantially from the version shown at the top of a documentation page, check the matching version’s docs before relying on a newer feature.


Implementation studio: document, import, call, verify

Spend about 15 minutes in a new notebook named documentation_practice.ipynb. Write the code yourself; do not ask an AI tool to generate the implementation. The goal is to practice the decision process that makes later AI assistance verifiable.

Use this small operational dataset:

daily_ticket_counts = [18, 23, 15, 30, 24]

Build the following short analysis:

  1. Use the built-in len() to count the number of observed days.
  2. Use the official documentation to confirm the module and function for an arithmetic mean.
  3. Import the module using the module-qualified style.
  4. Calculate the mean ticket count.
  5. Use math.log() with base 2 to calculate the base-2 logarithm of 1024.
  6. Print all three results with labels.

A good structure is:

import math
import statistics

daily_ticket_counts = [18, 23, 15, 30, 24]

# Write your three calculations below this line.

Your outputs should communicate these facts:

  • There are 5 observed days.
  • The mean ticket count is 22.0.
  • The base-2 logarithm of 1024 is 10.0.

Do not just compare printed output. Trace the types and roles of the values:

print(type(daily_ticket_counts))
print(type(statistics.mean(daily_ticket_counts)))
print(type(math.log(1024, 2)))

Finally, deliberately make and diagnose one realistic import error:

from statistics import mean

print(statistics.mean(daily_ticket_counts))

The error is not caused by a bad mean calculation. It comes from a mismatch between the import style and the later function call: this import created the name mean, not the name statistics. Correct it in one of two consistent ways:

  • keep from statistics import mean and call mean(...); or
  • replace the import with import statistics and call statistics.mean(...).

This is a small example of a broader professional habit: when code fails, identify which names actually exist in the current environment before changing unrelated lines.


Key takeaways

The standard library gives you useful functionality without additional installation, but you still need to select and call it deliberately.

  • Built-ins such as len() and sum() can be called directly.
  • Standard-library tools live in modules such as statistics, math, and glob, which you normally import first.
  • import statistics supports an explicit call such as statistics.mean(values).
  • from statistics import mean supports mean(values) but does not create the name statistics.
  • Use the official documentation to verify a function’s module, signature, accepted inputs, returned value or side effect, and important edge cases.
  • A tiny known-input test is the fastest way to check that an imported function behaves as expected.

Next, you will build a systematic approach to syntax errors, runtime errors, and logic errors. The name-resolution mistake in the final studio task is a useful preview: tracebacks are not just bad news; they identify the specific point where Python’s actual state differs from what your code assumed.

Can't find a good explanation? Sign up and we'll make it for you

Sign up