Python Tutorial · Working with Data · Lesson 31 of 42

Python Modules and Imports

Import standard-library modules, your own files and third-party packages.

Importing modules

A module is a Python file. Import it whole, import specific names, or give it an alias:

Example 1Try it yourself
import math
from statistics import mean, median
import datetime as dt

print(math.sqrt(16))
print(mean([2, 4, 9]), median([2, 4, 9]))
print(dt.date(2026, 1, 1).isoformat())

Output

4.0
5 4
2026-01-01

Your own modules

Any .py file is a module. If you have helpers.py next to your script, import helpers makes its functions available as helpers.name.

The __name__ == "__main__" check

Code inside this block runs only when the file is executed directly, not when it's imported:

def main():
    print("Running as a script")

if __name__ == "__main__":
    main()

The standard library

Python ships with modules for most everyday tasks: os, pathlib, json, csv, datetime, random, re, math, statistics, collections, itertools, urllib, sqlite3…

Example 2Try it yourself
from pathlib import Path
from collections import Counter
import itertools

print(Path("reports/2026/summary.csv").suffix)
print(Counter("mississippi").most_common(2))
print(list(itertools.combinations("ABC", 2)))

Output

.csv
[('i', 4), ('s', 4)]
[('A', 'B'), ('A', 'C'), ('B', 'C')]

Test yourself

Which statement imports only sqrt from the math module?

  1. import sqrt from math
  2. from math import sqrt
  3. import math.sqrt
  4. using math.sqrt
Show answer

Answer: from math import sqrt