The Python Standard Library: Dates, Counter, Statistics and More

Python for Beginners: Learn to Code with Real Projects · Objects, Libraries and Projects · 6 min read · Updated

Ready-made tools

  1. Many everyday jobs, like counting, grouping or date maths, have been solved before.
  2. Python includes tested tools for them in the standard library.
  3. You import the tool and use it in a few lines instead of writing your own version.
  4. You get a reliable result, and your code stays short and easy to read.

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 ...) is True because Ravi has 72, and all(s > 50 ...) is True.

Other modules worth knowing

  • json and csv for data files (lesson 8), pathlib and shutil for files and folders (lessons 8 and 14).
  • re for patterns in text, called regular expressions. They are powerful, but start with plain string methods.
  • argparse for command-line options (lesson 15) and logging for proper messages from bigger programs.
  • urllib.request for simple web requests. Many people install requests for a friendlier tool.
  • sqlite3 for a small database inside a file, with no server to install.
  • unittest for tests (lesson 15), and decimal for exact decimal maths, which matters for money.

How to find the right tool

  1. Describe the job in plain words, for example: group items by a key, or add days to a date.
  2. Search the official Python documentation, or search the web for Python plus your description.
  3. Read the short example in the documentation, and try it in the interactive prompt.
  4. Prefer the standard library, because it is installed everywhere and well maintained, before you add a package.

Your task

  1. Print how many days remain from today until a date you choose, such as your next birthday. Use date.today().
  2. Use Counter to find the three most common letters in a sentence you write.
  3. Use defaultdict(list) to group a list of words by their first letter.
  4. Make a list of names and a list of marks. Use zip and sorted to 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.

Frequently asked questions

Is random safe for passwords?

No. The random module is not designed for security. Use the secrets module for passwords and tokens.

What is the difference between mean and median?

The mean is the sum divided by the count. The median is the middle value after sorting. The median is less affected by a few very large or small values.