AI Hints
Home›Python Tutorial›Modern Classes and the Standard Library
Python · Lesson 20 of 49

Dates, Randomness and Collections

The most useful standard library tools.

⏱ 2 min read▶ Video at 1:04:09🎓 Free
Watch this lesson in the Python courseWatch on YouTube ↗Full Python course

Ava wants her program to say when an order was placed, how many days until a delivery, to pick a random winner for a monthly prize, and to count which plants sell best. Every one of those jobs is already solved, inside the standard library. Knowing what is there will save you thousands of lines of code.

Dates, Randomness and Collections
From the video: Dates, Randomness and Collections
  • Dates and times
  • Random choices
  • Smart counting and grouping

Dates with datetime

The datetime module handles dates and times. A date holds a day, and datetime adds the time. You can format them with strftime, and parse text with strptime. Subtracting two dates gives a timedelta, which tells you the number of days. And adding a timedelta moves a date forward.

dates.pypython
from datetime import date, timedelta, datetime

placed = date(2025, 3, 14)
delivery = placed + timedelta(days=5)
print(delivery)
print((delivery - placed).days)
print(delivery.strftime("%A, %d %B %Y"))
d = datetime.strptime("2025-12-25", "%Y-%m-%d")
print(d.weekday(), d.year)
Output
2025-03-19
5
Wednesday, 19 March 2025
3 2025

Random choices

The random module picks at random. Choice picks one item, sample picks several different ones, shuffle mixes a list in place, and randint gives a whole number in a range. Setting a seed makes the results repeatable, which is perfect for tests. Here Ava draws the monthly winner.

rand.pypython
import random

random.seed(7)
customers = ["Maya", "Sam", "Lee", "Ana", "Raj"]
print(random.choice(customers))
print(random.sample(customers, 2))
print(random.randint(1, 6))
random.shuffle(customers)
print(customers)
Output
Lee
['Sam', 'Ana']
6
['Sam', 'Ana', 'Lee', 'Raj', 'Maya']

Counter and defaultdict

The collections module has smarter containers. Counter counts items in one line, and finds the most common. Defaultdict creates missing entries automatically, so grouping needs no checks. Deque is a fast queue. And namedtuple gives tuples readable names. These replace many hand written loops.

collections1.pypython
from collections import Counter, defaultdict, deque

sold = ["fern", "ivy", "fern", "rose", "fern", "ivy"]
print(Counter(sold).most_common(2))

groups = defaultdict(list)
for name in sold:
    groups[name[0]].append(name)
print(dict(groups))

q = deque([1, 2, 3])
q.append(4)
print(q.popleft(), list(q))
Output
[('fern', 3), ('ivy', 2)]
{'f': ['fern', 'fern', 'fern'], 'i': ['ivy', 'ivy'], 'r': ['rose']}
1 [2, 3, 4]

Math and statistics

The statistics module computes averages, the median, and standard deviation. Math brings roots, logarithms, and trigonometry. And for money, the decimal module avoids floating point surprises, so that point one plus point two is exactly point three. Use the right tool for the job.

stats.pypython
import statistics as st
from decimal import Decimal

sales = [24, 9, 14, 40, 9]
print(st.mean(sales), st.median(sales), st.mode(sales))
print(round(st.stdev(sales), 2))
print(Decimal("0.1") + Decimal("0.2"))
Output
19.2 14 9
13.14
0.3

Other handy modules

A few more are worth remembering. Time pauses and measures. Os and shutil work with the operating system, and sys reads command line arguments. Argparse builds proper command line tools. Subprocess runs other programs. Textwrap, string and uuid help with text and unique identifiers. The standard library is enormous, so search it before you write.

time, sys, ospauses, arguments, system info
argparsebuild command line tools
subprocessrun other programs
uuid, secretsunique ids, safe tokens
urllib, httptalk to the web
zipfile, shutilarchives, copying

Best seller

Your turn. Given a list of sold plant names, use Counter to print the best selling plant, and how many were sold. Ready? Here is one solution. Counter, then most common with one, and unpack the first result.

✍️ Exercise: Best seller

Use Counter on the sold list and print the best seller with its count.

Show hint

Counter(...).most_common(1)

Show solution
best.pypython
from collections import Counter

sold = ["fern", "ivy", "fern", "rose", "fern"]
name, n = Counter(sold).most_common(1)[0]
print(name, n)
Output
fern 3

Summary

Well done. You can handle dates, pick randomly, count and group with collections, and compute statistics. You also saw how large the standard library is. Next, we meet a pair of modules that make your code shorter, and more elegant, itertools and functools.

Key takeaways
  • datetime, timedelta, strftime
  • random: choice, sample, shuffle
  • Counter and defaultdict
Next up: itertools and functools — power tools for iteration