Intermediate Python · Lesson 7 of 14

Modules and the standard library

Import modules in different ways, split code into your own files, and use Counter, defaultdict, namedtuple and itertools from the standard library.

About 18 minutes · code runs in your browser, nothing to install

A module is a Python file whose functions and variables you can use in another file. Python comes with hundreds of them, called the standard library, and import statement brings one into your program.

Pythoneditable
import math
print(math.sqrt(81))

from math import pi, floor
print(floor(pi * 100) / 100)

import statistics as st
print(st.median([3, 9, 4, 7, 5]))
Output
9.0
3.14
5

import math keeps the module name in front; from ... import takes single names; as gives a shorter name.

Tip: Avoid from module import *. It pours every name into your file, so you can no longer see where a name came from, and one module can silently overwrite another's names.

Your own modules

Any .py file is a module. Put functions in shop_tools.py and import them in main.py from the same folder. The block if __name__ == "__main__": runs only when the file is started directly, not when it is imported, which makes it a good home for quick tests.

Python · runs on your computer
# shop_tools.py
def add_vat(price, rate=0.2):
    return round(price * (1 + rate), 2)

if __name__ == "__main__":
    print(add_vat(10))  # runs only with: python shop_tools.py

# main.py (same folder)
# from shop_tools import add_vat
# print(add_vat(25))

Two files on your own computer: the page runs one file at a time.

Pythoneditable
print(__name__)
Output
__main__

The file you run is always called __main__.

collections.Counter: counting things

Counter counts how often each item appears. most_common(n) returns the top n as (item, count) pairs.

Pythoneditable
from collections import Counter

votes = ["pizza", "sushi", "pizza", "tacos", "sushi", "pizza"]
counts = Counter(votes)
print(counts)
print(counts["pizza"], counts["salad"])
print(counts.most_common(2))

letters = Counter("banana")
print(letters.most_common(1))
Output
Counter({'pizza': 3, 'sushi': 2, 'tacos': 1})
3 0
[('pizza', 3), ('sushi', 2)]
[('a', 3)]

A missing item counts as 0 instead of raising a KeyError.

defaultdict and namedtuple

A defaultdict creates a starting value the first time a key is used, so grouping needs no if key not in ... check. A namedtuple is a tuple whose parts also have names, which makes code that uses it easier to read.

Pythoneditable
from collections import defaultdict, namedtuple

sales = [("Lyon", 120), ("Graz", 80), ("Lyon", 45), ("Graz", 60), ("Cork", 30)]
by_city = defaultdict(list)
for city, amount in sales:
    by_city[city].append(amount)
print(dict(by_city))

City = namedtuple("City", ["name", "country", "population"])
c = City("Graz", "Austria", 300000)
print(c)
print(c.name, c.population)
name, country, _ = c
print(country)
Output
{'Lyon': [120, 45], 'Graz': [80, 60], 'Cork': [30]}
City(name='Graz', country='Austria', population=300000)
Graz 300000
Austria

itertools: tools for looping

itertools holds ready-made iterators. A few useful ones: chain joins several sequences, combinations picks every group of a given size, accumulate gives running totals and islice takes a slice from any iterator.

Pythoneditable
from itertools import chain, combinations, accumulate, islice, count

print(list(chain([1, 2], [3], [4, 5])))
print(list(combinations(["Ana", "Ben", "Cleo"], 2)))
print(list(accumulate([100, 50, -30, 20])))
print(list(islice(count(10, 5), 4)))
Output
[1, 2, 3, 4, 5]
[('Ana', 'Ben'), ('Ana', 'Cleo'), ('Ben', 'Cleo')]
[100, 150, 120, 140]
[10, 15, 20, 25]

✎ Exercise

Count the words in the sentence (ignore upper/lower case) and print the two most common words with their counts.

Hint: Lower the text, split it into words and pass the list to Counter.

Your codewrite your answer, then Run
from collections import Counter

text = "The cat and the dog and THE bird"
# your code here

Expected output:

[('the', 3), ('and', 2)]
Show a solution
Solutioneditable
from collections import Counter

text = "The cat and the dog and THE bird"
counts = Counter(text.lower().split())
print(counts.most_common(2))
Output
[('the', 3), ('and', 2)]

Check yourself

1. What does Counter("hello")["z"] return?

2. When does the code under if __name__ == "__main__": run?

3. Which import lets you write sqrt(16) without a prefix?

Spotted a mistake on this page? Tell us