Skip to content
Visual explainer 4h to learn 5 steps

collections, itertools, datetime & random

Reach for Counter, defaultdict, itertools and datetime instead of reinventing them.

By Invicly Tech, , in Python Programming from Zero. About 11 minutes to read.

Topic 21 of 34

In short

Python ships with a rich standard library. Counter and defaultdict simplify counting and grouping, itertools combines and slices iterables, datetime handles dates and times, and random makes samples and choices.

Explained simply

Python is often called "batteries included". It ships with hundreds of ready-made modules, called the standard library, that you can import without installing anything. Before you write a helper function yourself, it is worth asking: does Python already have this?

Four modules cover a surprising amount of daily work. collections has smarter containers, like Counter for counting things and defaultdict for grouping. itertools has building blocks for loops, like joining several lists or grouping neighbours. datetime handles dates, times and durations. random picks, shuffles and samples.

Using these tools makes your code shorter and also more correct. Counter already handles a missing key. datetime already knows that February has 28 or 29 days and that clocks change in spring. Your hand-written version might not.

A good habit: when you write a loop that counts, groups, pairs up items or does maths with dates, stop and check these four modules first. Experienced Python developers read and recognise this style instantly, so it also makes your code easier for others.

Press Play on a diagram to walk through it one step at a time.

MapEveryday standard library tools
Standard library
  • collections
    • Counter
    • defaultdict
    • deque
    • namedtuple
  • itertools
    • chain
    • groupby
    • islice
    • combinations
  • datetime
    • date
    • datetime
    • timedelta
    • strptime / strftime
  • random
    • choice
    • sample
    • shuffle
    • seed
ComparePicking items with random
choices(seq, k=n)
  • With replacement
  • Repeats possible
  • Supports weights=
  • k can exceed len(seq)
sample(seq, k=n)
  • Without replacement
  • No position picked twice
  • Returns a new list
  • k must be at most len(seq)
shuffle(lst)
  • Reorders all items
  • Changes the list in place
  • Returns None
  • Needs a mutable list
FlowFrom user text to a correct stored time
  1. 1
    Parse text

    strptime("30/03/2027 09:30", "%d/%m/%Y %H:%M")

  2. 2
    Attach the zone

    .replace(tzinfo=ZoneInfo("Europe/Berlin"))

  3. 3
    Convert to UTC

    .astimezone(timezone.utc)

  4. 4
    Store as ISO text

    .isoformat() gives 2027-03-30T07:30:00+00:00

  5. 5
    Display locally

    .astimezone(viewer_zone) when showing it

In depth

Counter: more than a counting dict

Counter is a dict subclass where each key maps to a count. Asking for a missing key returns 0 instead of raising KeyError, and it does not add the key. You can build one from any iterable, including a generator, so Counter(line.split()[0] for line in f) counts the first word of every line in a file without building a list.

Counters support maths. c.update(more) adds counts, c.subtract(other) removes them, and c1 + c2 combines two counters (dropping zero and negative results). most_common(3) returns the top three (item, count) pairs, sorted by count. c.total() (Python 3.10+) sums all the counts. Because it is still a dict, json.dumps(c) works directly.

  • Counter("banana") gives Counter({'a': 3, 'n': 2, 'b': 1})
  • c["missing"] returns 0 and does not insert the key
  • c.most_common()[-1] is the least common item

defaultdict, and the read that inserts

defaultdict(factory) calls factory() the first time you use a missing key with square brackets, stores the result, and returns it. defaultdict(list) gives an empty list, defaultdict(int) gives 0, defaultdict(set) gives an empty set. That is why groups[key].append(x) works without any if statement.

The surprise: even reading groups["nope"] inserts "nope" with an empty list. If you only want to check, use "nope" in groups or groups.get("nope"), which do not call the factory. When you are done building, convert with dict(groups) before returning it, so callers do not get the auto-insert behaviour by accident. A plain dict with setdefault(key, []).append(x) does the same job without a special type.

FlowWhat groups[key] does on a defaultdict(list)
  1. Step 1
    Key present?

    Yes: return the stored list

  2. Step 2
    Call list()

    No: make a new empty list

  3. Step 3
    Store it

    groups[key] now exists

  4. Step 4
    Return it

    So .append(x) works at once

itertools: lazy building blocks

Most itertools functions return iterators, which produce values only when asked. That keeps memory low even for huge inputs. chain(a, b) walks through several iterables as if they were one. islice(it, 10) takes the first 10 items of anything, even an endless generator. accumulate([3, 1, 4]) gives running totals 3, 4, 8. pairwise (3.10+) gives neighbours: (a, b), (b, c). batched(it, 100) (3.12+) yields tuples of 100, handy for sending data to an API in chunks.

groupby(data, key=f) is the one that trips people up. It starts a new group every time the key changes, so unsorted data gives the same key many times. Sort by the same key first. Also, each group is itself an iterator that is used up when groupby moves on, so turn it into a list right away if you need it later.

  • product("ab", repeat=2): aa, ab, ba, bb
  • combinations([1, 2, 3], 2): (1, 2), (1, 3), (2, 3)
  • count(1) counts forever; pair it with islice or zip

datetime: naive, aware and time zones

A naive datetime has no time zone; it is just a wall-clock reading. An aware datetime carries tzinfo and points to one exact moment. Comparing or subtracting a naive and an aware value raises TypeError, so pick one style. The safe rule: store and compute in UTC, convert to local time only for display.

datetime.now(timezone.utc) gives the current aware UTC time. The zoneinfo module (Python 3.9+) gives real time zones with daylight saving rules: ZoneInfo("Europe/Berlin"). On Windows, install the tzdata package for it to work. Parse ISO text with datetime.fromisoformat, and other formats with strptime and codes like %d/%m/%Y %H:%M. Subtracting two datetimes gives a timedelta; .total_seconds() turns it into a number.

  • strptime: string parse time (text to datetime)
  • strftime: string format time (datetime to text)
  • %Y year, %m month, %d day, %H hour (24h), %M minute, %S second
  • date.today() and datetime.now() are naive local time

random: choose the right function, and when not to use it

random.choice(seq) picks one item. random.choices(seq, k=5) picks five with replacement, so repeats are possible, and accepts weights=[...] for unequal odds. random.sample(seq, 5) picks five different positions, without replacement. random.shuffle(lst) reorders a list in place and returns None, a classic bug when written as lst = random.shuffle(lst). random.randint(1, 6) includes both ends, while randrange(1, 6) stops before 6.

random.seed(42) makes the sequence repeatable, which is great for tests and simulations. For anything secret, such as passwords, reset links or API tokens, use the secrets module instead: secrets.token_urlsafe(32) or secrets.choice(alphabet). The random module is predictable by design, so an attacker who sees enough outputs can work out the rest.

Learn it in 5 short steps

About 50m each. Track them with a timer in your plan.

  1. 1
    Count items with Counter~50m
  2. 2
    Group data with defaultdict~50m
  3. 3
    Chain and group with itertools~50m
  4. 4
    Parse and format dates with datetime~50m
  5. 5
    Generate random samples with random~50m

Key points

  • Counter(words).most_common(3) gives the three most frequent items.
  • defaultdict(list) creates an empty list for a new key automatically.
  • itertools.groupby only groups adjacent items, so sort by the same key first.
  • strptime parses text into a datetime; strftime formats a datetime as text.
  • random.seed(42) makes random results repeatable for tests.

Key terms

Tap a card to flip it. 0/5 known

Examples

python
from collections import Counter, defaultdict
from datetime import datetime, timedelta
import itertools, random

words = "a b a c b a".split()
print(Counter(words).most_common(2))     # [('a', 3), ('b', 2)]
by_len = defaultdict(list)
for w in ["hi", "yo", "cat"]:
    by_len[len(w)].append(w)

print(list(itertools.chain([1, 2], [3])))  # [1, 2, 3]

d = datetime.strptime("2026-03-01", "%Y-%m-%d")
print((d + timedelta(days=30)).strftime("%d %b %Y"))  # 31 Mar 2026
random.seed(1); print(random.choice(words))

Summarising a web server log

Each line has a method, a path and a status code. Step 1: Counter counts status codes straight from a generator expression. Step 2: defaultdict(set) groups the paths by status, and a set removes duplicates. Step 3: most_common(2) shows the busiest codes, and the 500 group tells you which page is failing.

python
from collections import Counter, defaultdict

lines = [
    "GET /home 200", "GET /login 500", "POST /login 200",
    "GET /home 200", "GET /cart 404", "GET /login 500",
]
status = Counter(line.split()[2] for line in lines)
paths_by_status = defaultdict(set)
for line in lines:
    _, path, code = line.split()
    paths_by_status[code].add(path)

print(status.most_common(2))           # [('200', 3), ('500', 2)]
print(sorted(paths_by_status["500"]))  # ['/login']

One meeting, three time zones

A meeting is set for 09:30 in Berlin on 30 March 2027, just after Europe switches to summer time (UTC+2). Step 1: create an aware datetime with ZoneInfo. Step 2: astimezone shows it in India (UTC+5:30) and in UTC. Step 3: subtract the current UTC time to get a timedelta until the meeting. Both sides are aware, so the subtraction is allowed.

python
from datetime import datetime, timezone
from zoneinfo import ZoneInfo

start = datetime(2027, 3, 30, 9, 30, tzinfo=ZoneInfo("Europe/Berlin"))
print(start.astimezone(ZoneInfo("Asia/Kolkata")))  # 2027-03-30 13:00:00+05:30
print(start.astimezone(timezone.utc).isoformat())  # 2027-03-30T07:30:00+00:00

left = start - datetime.now(timezone.utc)
print(f"{left.days} days and {left.seconds // 3600} hours to go")

Quick reference

  • Counter(items).most_common(n) gives the top n (item, count) pairs
  • defaultdict(list): groups[k].append(x) with no key check; even reading groups[k] inserts k
  • Sort by the same key before itertools.groupby, or groups repeat
  • islice(it, n) takes the first n items of any iterator, even an endless one
  • Store datetimes in UTC: datetime.now(timezone.utc); show local with astimezone(ZoneInfo(...))
  • datetime - datetime gives a timedelta; use .total_seconds() for a number
  • random.shuffle returns None; random.randint(a, b) includes b
  • Use secrets, not random, for passwords and tokens

Common mistakes

  • Using groupby on unsorted data and getting many tiny groups.
  • Mixing naive and timezone-aware datetimes in comparisons.
  • Using random for passwords or tokens; use the secrets module.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1c = Counter("aab"). What does c["z"] return?

Question 2

2You run groupby on ["a", "b", "a"] without sorting. How many groups do you get?

Question 3

3Which call can return the same item twice?

Question 4

4What happens when you subtract a naive datetime from an aware one?

Question 5

5groups = defaultdict(list). After print(groups["x"]), what is len(groups)?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Given a sentence, print the three most common words, ignoring case.

  2. Exercise 2medium

    Given a list of (name, team) tuples, build a dict mapping each team to a sorted list of names. Then do it a second way with itertools.groupby.

  3. Exercise 3hard

    Write days_until_birthday(birthday: date, today: date) that returns how many days until the next birthday. Handle a birthday that already passed this year, and 29 February in non-leap years (use 1 March).

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Is the standard library always installed?
Yes, it comes with every normal Python installation, so you never pip install collections or datetime. Some Linux distributions split a few modules (like venv or tkinter) into separate system packages.
Should I use datetime or a library like Arrow or Pendulum?
Start with datetime plus zoneinfo; since Python 3.9 they cover time zones well. Reach for a library only if you need features like natural language parsing.
What is the difference between a dict with get() and a defaultdict?
d.get(k, default) only returns a default and leaves d unchanged. A defaultdict creates and stores the default, which is what you want when building groups or counts.
Why does random give the same numbers every run?
Something called random.seed() with a fixed value, often in test setup. Remove the seed call, or call random.seed() with no argument to reseed from the system.

Go deeper

ShareXLinkedInWhatsApp