The Python standard library

A tour of a few modules

You'll use each of these in the problems ahead — this is a quick reference, not something to memorize.

math

import math

math.sqrt(16)     # 4.0
math.ceil(4.1)     # 5    (round up to the nearest integer)
math.floor(4.9)    # 4    (round down to the nearest integer)
math.pi            # 3.141592653589793

statistics

import statistics

statistics.mean([1, 2, 3, 4])     # 2.5
statistics.median([1, 3, 5])      # 3      (the middle value)
statistics.median([1, 2, 3, 4])   # 2.5    (average of the two middle values, for an even count)

collections.Counter

Counter is one of the most useful tools in the standard library — it counts occurrences of items for you, so you don't have to hand-write a counting dict:

from collections import Counter

Counter(["a", "b", "a", "c", "a"])
# Counter({'a': 3, 'b': 1, 'c': 1})

c = Counter(["a", "b", "a", "c", "a"])
c.most_common(1)   # [('a', 3)]  -- the single most common item, with its count
c.most_common(2)   # [('a', 3), ('b', 1)]  -- the top 2

most_common(n) returns a list of (item, count) tuples, sorted from most frequent to least.

datetime

from datetime import datetime

d = datetime.strptime("2024-03-05", "%Y-%m-%d")   # parse a date string
d.year    # 2024
d.month   # 3
d.day     # 5
d.strftime("%B")   # "March"  -- full month name

strptime ("string parse time") turns a formatted string into a datetime object; strftime ("string format time") does the reverse. The format codes (%Y for a 4-digit year, %m for a zero-padded month, %d for a zero-padded day, %B for a full month name) are worth recognizing but not worth memorizing — you'll look them up when you need them, same as any working programmer does.

The pattern across all of these is the same: import the module, then call into it with a dot. Once that clicks, picking up any other standard library module later is just a matter of reading its documentation.