After this lesson, you will be able to: Use the Python standard library effectively: collections, itertools, functools, datetime, os, subprocess.
Python ships with a vast standard library. Knowing what's there means not reinventing wheels.
Beyond dict and list.
from collections import Counter, defaultdict, deque, namedtuple# Counter, count occurrenceswords = "the quick brown fox the lazy dog".split()Counter(words).most_common(3)# [('the', 2), ('quick', 1), ('brown', 1)]# defaultdict, auto-create missing keysby_tag = defaultdict(list)for item in items:by_tag[item.tag].append(item)# No KeyError; auto-creates [] on first access# deque, O(1) append/pop on both endsq = deque(maxlen=100) # ring bufferq.append("new")q.popleft()# namedtuple, lightweight classPoint = namedtuple("Point", ["x", "y"])p = Point(1, 2)
Powerful combinators.
from itertools import chain, groupby, islice, pairwise, batchedlist(chain([1,2], [3,4])) # [1, 2, 3, 4]list(islice(range(100), 5, 10)) # [5,6,7,8,9]list(pairwise([1,2,3,4])) # [(1,2),(2,3),(3,4)]list(batched([1,2,3,4,5,6,7], 3)) # [(1,2,3),(4,5,6),(7,)]from functools import reduce, lru_cache, partialreduce(lambda a, b: a*b, range(1, 5)) # 24 (factorial of 4)@lru_cache(maxsize=128)def expensive(n): return slow_compute(n)add5 = partial(lambda a, b: a + b, 5)add5(10) # 15
Two pieces every script needs eventually.
from datetime import datetime, timedelta, timezonenow = datetime.now(timezone.utc) # always work in UTCtomorrow = now + timedelta(days=1)now.isoformat()datetime.fromisoformat("2026-05-23T10:00:00+00:00")# subprocess (calling other programs)import subprocessresult = subprocess.run(["git", "log", "-n", "5", "--oneline"],capture_output=True, text=True, check=True,)print(result.stdout)# Never pass shell=True with user input (command injection)
Reinventing Counter or defaultdict by hand. Naive datetime (no timezone). Causes off-by-one-day bugs at edges. ALWAYS use timezone-aware. subprocess with shell=True + user input. Command injection. Always pass a list. Forgetting check=True on subprocess.run. Failure goes unnoticed.
Pick the cleanest answer.
Sign in and purchase access to unlock this lesson.