Libraries introduction

Libraries

Everything you've written so far has used only Python's built-in functions — len(), str(), range(), and so on. But Python ships with a huge amount of additional, ready-to-use functionality called the standard library: modules for math, dates, randomness, file paths, data structures, and much more, all installed alongside Python itself, no extra setup needed.

import

To use a module, import it by name at the top of your file:

import math

math.sqrt(16)   # 4.0
math.pi          # 3.141592653589793

Everything the module provides is accessed with a dot: math.sqrt, math.pi, math.ceil, and so on. This dotted access is called a namespace — it keeps math's sqrt separate from, say, a sqrt function you might define yourself, so they never collide.

Importing specific names

You can also import just the pieces you need, so you don't have to prefix every call with the module name:

from math import sqrt, ceil

sqrt(16)   # 4.0, no "math." prefix needed

Both styles are common. import math (then math.sqrt(...)) is usually clearer about where a function comes from, especially in a file that uses several modules — that's the style this section will mostly use.

Why this matters

A huge amount of real-world programming is knowing what's already built so you don't reinvent it. Need the current date? datetime. Need to count how often things appear in a list? collections.Counter. Need the median of a set of numbers? statistics.median. The next few problems introduce exactly these — not because you couldn't write them yourself (you could, with what you already know), but because knowing they exist saves you the trouble.