Warming up the neural circuits...
By the end of this chapter you will:
The best code is the code you don't write. Python's standard library has batteries for almost everything — counting, dates, text processing, math, and more. Before importing a third-party package, check if the stdlib already solves your problem.
from collections import Counter, defaultdict, deque
# Counter — count occurrences
words = ["apple", "banana", "apple", "cherry", "banana", "apple"]
counts = Counter(words)
print(counts) # Counter({'apple': 3, 'banana': 2, 'cherry': 1})
print(counts.most_common(2)) # [('apple', 3), ('banana', 2)]
# defaultdict — dict with default values
groups = defaultdict(list)
for word in words:
groups[len(word)].append(word)
print(groups) # {5: ['apple'], 6: ['banana', 'cherry']}
# deque — fast append/pop from both ends
dq = deque([1, 2, 3])
dq.appendleft(0) # [0, 1, 2, 3]
dq.pop() # [0, 1, 2]| Class | Use when |
|---|---|
Counter | Counting occurrences |
defaultdict | Dict with default values |
deque | Fast operations |
import itertools
# chain — combine iterables
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined = list(itertools.chain(list1, list2))
# [1, 2, 3, 4, 5, 6]
#
from datetime import datetime, date, timedelta
# Current date/time
now = datetime.now()
today = date.today()
# Parse strings
dt = datetime.strptime("2024-01-15 10:30", "%Y-%m-%d %H:%M
import re
# Search
text = "My phone is 555-1234"
match = re.search(r'\d{3}-\d{4}', text)
print(match.group()) # '555-1234'
#
import os
import sys
import random
import math
# os — operating system
os.getcwd() # current directory
os.listdir(".") # list files
os.environ.get("KEY")
The standard library is your toolbox:
| Mistake | Why it's wrong | Fix |
|---|---|---|
datetime.now() without timezone | Naive datetime, no timezone info | Use datetime.now(timezone.utc) |
re.search(pattern, text) in loop | Recompiles pattern each time | Use re.compile(pattern) first |
random.seed() not set | Results not reproducible | Set seed for testing |
Importing * from collections | Pollutes namespace | Import specific names |
Counter({'apple': 2, 'banana': 1, 'cherry': 1}){5: ['apple'], 2: ['hi', 'go'], 6: ['banana']}Beginner:
"What is Counter used for?"
Counter counts occurrences of items in an iterable. It returns a dict-like object with items as keys and counts as values. Use
most_common(n)to get the top n items.
"What's the difference between datetime and date?"
datetimerepresents a date and time (year, month, day, hour, minute, second).daterepresents only a date (year, month, day). Usedatetimewhen time matters,datewhen only the day matters.
Senior:
"When would you use itertools over a list comprehension?"
itertools functions are lazy — they yield items one at a time, not building a list in memory. Use them for large datasets where you don't need all items at once. List comprehensions are better when you need the full result.
"What's the difference between re.search() and re.match()?"
search()finds the pattern anywhere in the string.match()only matches at the beginning of the string. Use for finding patterns, for validating that a string starts with a pattern.
collections.Counter — count occurrences. defaultdict — dict with defaults.itertools.chain — combine iterables. groupby — group consecutive items.datetime — dates and times. timedelta — date arithmetic.re.search — find pattern. re.findall — find all. re.sub — replace.I want to…
├── Count items → Counter(list)
├── Default dict → defaultdict(list)
├── Combine iterables → chain(a, b)
├── Handle dates → datetime.now()
├── Find pattern → re.search(pattern, text)
├── Random → random.randint(1, 10)
└── Math → math.sqrt(16)What does Counter(['a', 'b', 'a']) return?
| Function | Use when |
|---|---|
chain | Combine iterables |
islice | Slice iterables |
groupby | Group consecutive items |
combinations | All pairs/triples |
| Class | Use when |
|---|---|
datetime | Date + time |
date | Date only |
time | Time only |
timedelta | Date arithmetic |
| Function | Use when |
|---|---|
search | Find first match |
findall | Find all matches |
sub | Replace matches |
compile | Reuse pattern |
search()match()