Python is often described as coming with *batteries included*. The standard library has tools for many everyday jobs, and learning them saves you hours. Instead of writing your own date maths, counting loops and averages, you use code that thousands of people have tested. This lesson is a tour of the tools that beginners need most. Each one appears in the program below with its real output.
from collections import Counter, defaultdict
from datetime import date, timedelta
import random
import statistics
start = date(2026, 1, 31)
print(start.strftime("%d %B %Y"), start.weekday()) # 0 is Monday
print(start + timedelta(days=30))
print((date(2026, 3, 1) - start).days, "days between")
print(date.fromisoformat("2026-02-14").isoformat())
votes = ["tea", "coffee", "tea", "juice", "tea", "coffee"]
print(Counter(votes).most_common(2))
groups = defaultdict(list)
for name, city in [("Asha", "Pune"), ("Ravi", "Delhi"), ("Meena", "Pune")]:
groups[city].append(name)
print(dict(groups))
marks = [72, 85, 90, 66, 85]
print(statistics.mean(marks), statistics.median(marks), statistics.mode(marks))
random.seed(7)
picked = random.choice(["a", "b", "c"])
print(picked in ["a", "b", "c"], len(random.sample(range(100), 5)))
names = ["Asha", "Ravi", "Meena"]
scores = [90, 72, 85]
for n, s in zip(names, scores):
print(n, s)
ranked = sorted(zip(names, scores), key=lambda pair: pair[1], reverse=True)
print(ranked)
print(any(s < 75 for s in scores), all(s > 50 for s in scores))
31 January 2026 5
2026-03-02
29 days between
2026-02-14
[('tea', 3), ('coffee', 2)]
{'Pune': ['Asha', 'Meena'], 'Delhi': ['Ravi']}
79.6 85 85
True 5
Asha 90
Ravi 72
Meena 85
[('Asha', 90), ('Meena', 85), ('Ravi', 72)]
True True
Dates and times
date(2026, 1, 31) makes a date. strftime turns it into text in the format you choose: %d is the day, %B the month name and %Y the year. weekday() gives 0 for Monday up to 6 for Sunday, so 31 January 2026 is a 5, a Saturday. You can add time with timedelta(days=30), and subtracting two dates gives a timedelta whose .days is the number of days. date.fromisoformat("2026-02-14") reads a date written as year, month and day. Use datetime instead of date when you also need the time, and date.today() or datetime.now() for the current moment.
Counting: Counter
Counter(votes) counts how often each value appears, and .most_common(2) gives the top two as pairs. It does in one line what you wrote with a loop in lesson 5.
Grouping: defaultdict
A defaultdict(list) is a dictionary that creates an empty list the first time you use a new key. That makes grouping easy: groups[city].append(name). The result is a dictionary from each city to the list of names. Wrap it in dict(...) when you print it, so it looks normal.
Statistics
statistics.mean, median and mode give the average, the middle value and the most common value. For the marks 72, 85, 90, 66 and 85, the mean is 79.6, the median is 85 and the mode is 85. The median is often a better picture of a typical value than the mean when a few values are very large or very small.
Random
The random module makes pseudo-random numbers. random.choice(list) picks one item, random.sample(range(100), 5) picks five different numbers and random.randint(1, 6) rolls a die. random.seed(7) makes the sequence repeatable, which is useful for tests. The numbers are not safe for passwords or security tokens. For those, use the secrets module.
zip, sorted and key functions
zip(names, scores)pairs up items from two lists, which is perfect for looping over both at once.sorted(items, key=..., reverse=True)sorts by any rule you give. In the example,key=lambda pair: pair[1]sorts the pairs by the score, highest first.any(...)is true if at least one item meets the condition.all(...)is true if every item does. In the output,any(s < 75 ...)isTruebecause Ravi has 72, andall(s > 50 ...)isTrue.
Other modules worth knowing
jsonandcsvfor data files (lesson 8),pathlibandshutilfor files and folders (lessons 8 and 14).refor patterns in text, called regular expressions. They are powerful, but start with plain string methods.argparsefor command-line options (lesson 15) andloggingfor proper messages from bigger programs.urllib.requestfor simple web requests. Many people installrequestsfor a friendlier tool.sqlite3for a small database inside a file, with no server to install.unittestfor tests (lesson 15), anddecimalfor exact decimal maths, which matters for money.
How to find the right tool
- Describe the job in plain words, for example: group items by a key, or add days to a date.
- Search the official Python documentation, or search the web for Python plus your description.
- Read the short example in the documentation, and try it in the interactive prompt.
- Prefer the standard library, because it is installed everywhere and well maintained, before you add a package.
Your task
- Print how many days remain from today until a date you choose, such as your next birthday. Use
date.today(). - Use
Counterto find the three most common letters in a sentence you write. - Use
defaultdict(list)to group a list of words by their first letter. - Make a list of names and a list of marks. Use
zipandsortedto print them from the highest mark to the lowest.
How to check it worked
- Your day count is correct when you check it on a calendar.
- The most common letters match a count by hand.
- The names print in the order of their marks, highest first.