Skip to content
Visual explainer 4h to learn 5 steps

Practice: small data problems

Solve ten beginner exercises combining loops, lists and dicts without help.

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

Topic 13 of 34

In short

Practice turns syntax into skill. Each small problem follows the same loop: understand the input and output, plan with the right data structure, code it, then test normal and edge cases.

Explained simply

Reading about lists and dicts is not the same as using them. This topic is about practice: small problems that appear again and again in real code, such as filtering, counting, grouping and cleaning text. Solving them without help is what turns syntax into skill.

Each problem follows the same routine. Understand what goes in and what should come out, choose the data structure, write a small function, then test it with normal and unusual input. Most solutions are a function of five to ten lines.

A handful of patterns covers most beginner problems. Filtering is a loop with an if, or a comprehension. Counting uses dict.get() or Counter. Grouping uses setdefault() or defaultdict. Text problems use lower(), split() and strip().

Test every solution with assert lines, including odd cases: an empty list, a single item, ties, capital letters, punctuation. When all the asserts pass, close your notes and solve the same problem again the next day. If you can, you have really learned it.

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

CycleSolving one exercise
  1. 1
    Restate the problem

    Write the input, output and one example

  2. 2
    Pick a structure

    List to keep order, dict to count, set for uniques

  3. 3
    Write the code

    Small function with a clear name

  4. 4
    Test edge cases

    Empty input, one item, duplicates, odd casing

  5. 5
    Refine

    Simplify, rename, then try the next exercise

  6. Back to step 1
CompareThree ways to count words
if/else in a loop
  • if w in counts: counts[w] += 1
  • else: counts[w] = 1
  • Most explicit
  • Good for learning
dict.get()
  • counts[w] = counts.get(w, 0) + 1
  • One line in the loop
  • Plain dict result
  • Everyday choice
Counter
  • Counter(words)
  • No loop needed
  • most_common(n) built in
  • Best in real code

In depth

Four patterns behind most beginner problems

Almost every small data problem is one of four shapes, or two of them chained together. Filter keeps some items and drops others. Transform turns each item into something else. Aggregate boils many items down to one answer: a count, a total, a minimum or maximum. Group sorts items into buckets by some key, often followed by an aggregate per bucket.

The wording of the problem usually gives the pattern away. "Only", "which" and "remove" suggest a filter. "Convert", "each" and "format" suggest a transform. "How many", "total" and "most" suggest an aggregate. "By", "per" and "for each kind of" suggest grouping.

Naming the pattern before you code is a big shortcut: you go straight to the matching tool instead of staring at a blank editor.

MapFrom problem words to pattern and tool
Problem statement
  • only, which, remove
    • Filter
    • if inside a loop or comprehension
  • convert, each, format
    • Transform
    • [f(x) for x in items]
  • how many, total, most
    • Aggregate
    • len, sum, max, Counter
  • by, per, for each kind
    • Group
    • setdefault or defaultdict(list)

Choosing the data structure

Pick the structure by the question you need to answer quickly. Need order and duplicates, such as a sequence of readings? Use a list. Need to look things up by a key or keep a count per key? Use a dict. Need uniqueness or fast "is it in here?" checks? Use a set. Need one fixed record? Use a tuple.

The choice can change speed dramatically. Finding which of 10,000 emails also appear in another list of 10,000 with a nested loop, or with in on a list, can take up to 100 million comparisons. Turning the second list into a set first makes each check almost instant, so the whole job takes about 20,000 steps.

You do not need complexity theory yet. Just remember: in on a list inside a loop is a warning sign; convert to a set or dict first.

CompareCommon emails in two lists of 10,000
Nested loop or list in
  • for e in a: if e in b
  • Each check scans b
  • Up to 100 million comparisons
  • Seconds or worse
Set first
  • b_set = set(b)
  • Each check is a hash lookup
  • About 20,000 steps
  • Milliseconds

An edge-case checklist

Most wrong solutions work on the example in the problem and fail on input nobody thought about. Before you call a solution done, run it against this list.

Empty input: an empty list, empty string or empty dict. One item. All items the same. Ties, such as two words with the same top count: which one should win? Case and spacing: "Apple", "apple " and "APPLE". Punctuation stuck to words, like "end.". Zero, negative numbers and very large numbers.

For each case, decide the expected behaviour first, then write an assert for it. Sometimes the right answer is not obvious, such as the maximum of an empty list. Choose deliberately: return None, return a default, or raise ValueError with a clear message, and write that choice in the docstring.

  • Empty, one item, all equal
  • Ties and their order
  • Case, spaces and punctuation
  • Zero, negatives, very large values

Testing with assert

assert condition raises AssertionError when the condition is False and does nothing when it is True. That makes it the quickest possible test: assert count_vowels("Hello") == 2. Add a message to see what went wrong: assert result == 3, f"got {result}".

Write two or three asserts before writing the function. It forces you to pin down the exact output format, such as a list or a dict, sorted or not, before you get lost in code. When order does not matter, compare sorted(result) == sorted(expected) or compare sets.

When an assert fails, print the intermediate values, or open the function in the VS Code debugger and step through one line at a time. Later in this path you will move these asserts into pytest, which runs them all and gives a clear report; the habit you build now carries straight over.

Ten exercises to finish without help

Work through these in order, each as a function with at least three asserts. 1: return the even numbers from a list. 2: return words longer than n letters. 3: count the vowels in a string. 4: find the three most common words in a text, ignoring case. 5: group words by length. 6: remove duplicates while keeping the original order. 7: find the second largest unique number, or None. 8: check whether two words are anagrams. 9: merge two dicts of totals, adding values for shared keys. 10: find all pairs in a list that add up to a target.

Give each one 15 to 20 minutes of real effort before looking at a hint. Then solve it a second way, for example with a loop and then with a comprehension or Counter. Read other people's solutions only after yours passes. Redo any you needed help with two days later.

Learn it in 5 short steps

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

  1. 1
    Solve list filtering exercises~50m
  2. 2
    Solve counting and grouping exercises~50m
  3. 3
    Solve string processing exercises~50m
  4. 4
    Check solutions against edge cases~50m
  5. 5
    Finish ten exercises without help~50m

Key points

  • Most beginner problems are filter, count, group or transform.
  • Wrap each solution in a function so you can call it with test inputs.
  • Always try the empty input and a single-item input.
  • Struggle for 15 minutes before peeking at hints; that effort builds memory.

Key terms

Tap a card to flip it. 0/4 known

Examples

python
def group_by_length(words):
    """Group words by their length."""
    groups = {}
    for w in words:
        groups.setdefault(len(w), []).append(w)
    return groups

assert group_by_length([]) == {}
assert group_by_length(["a"]) == {1: ["a"]}
assert group_by_length(["hi", "yo", "cat"]) == {2: ["hi", "yo"], 3: ["cat"]}
print("all good")

Write a few asserts for edge cases before calling it done.

Second largest unique number

The problem: return the second largest distinct number, or None if there is none. Step 1: decide the edge cases first: duplicates of the maximum must not count, and lists with fewer than two distinct values give None. Step 2: set() removes duplicates, and sorting in reverse puts the largest first. Step 3: return index 1 only when it exists. Step 4: asserts cover duplicates, too few values, an empty list and negative numbers.

python
def second_largest(nums):
    """Return the second largest distinct number, or None."""
    unique = sorted(set(nums), reverse=True)
    return unique[1] if len(unique) >= 2 else None

assert second_largest([4, 1, 4, 3]) == 3
assert second_largest([5, 5]) is None
assert second_largest([]) is None
assert second_largest([-2, -7]) == -7
print("all good")

Grouping anagrams

Find groups of words that use the same letters. Step 1: recognise the pattern: group by a key. Step 2: the key is the word's letters in sorted order, lower-cased, so "listen" and "Silent" both give "eilnst". Step 3: setdefault() collects words per key. Step 4: keep only groups with more than one word. Step 5: test the empty input too.

python
def anagram_groups(words):
    """Return lists of words that are anagrams of each other."""
    groups = {}
    for w in words:
        key = "".join(sorted(w.lower()))
        groups.setdefault(key, []).append(w)
    return [g for g in groups.values() if len(g) > 1]

print(anagram_groups(["listen", "Silent", "enlist", "google", "cat", "act"]))
# [['listen', 'Silent', 'enlist'], ['cat', 'act']]
assert anagram_groups([]) == []

Quick reference

  • Filter: [x for x in items if test(x)]
  • Count: counts[k] = counts.get(k, 0) + 1, or simply Counter(items)
  • Group: groups.setdefault(key, []).append(item)
  • Remove duplicates but keep order: list(dict.fromkeys(items))
  • Using in inside a loop? Make the other collection a set first
  • Order does not matter? Compare sorted(result) == sorted(expected)
  • Always test: empty input, one item, duplicates, ties and mixed case
  • max(d, key=d.get) returns the key with the biggest value

Common mistakes

  • Testing only the happy path from the problem statement.
  • Copying a solution without retyping and understanding it.
  • Using index-based loops where a direct for item in items is simpler.

Quick quiz

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

Question 1

1Which tool best answers "which emails appear in both lists?"

Question 2

2What does list(dict.fromkeys([3, 1, 3, 2, 1])) return?

Question 3

3A task says "total sales per region". Which pattern is it?

Question 4

4Checking each of 10,000 items with in against a 10,000-item list takes about how many comparisons in the worst case?

Question 5

5counts = {"a": 2, "b": 5}. What does max(counts, key=counts.get) return?

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

    Write evens_above(nums, limit) that returns the even numbers greater than limit, in their original order. Test it with a normal list, an empty list and a list with no matches.

  2. Exercise 2medium

    Write top_words(text, n) that returns the n most common words as (word, count) pairs, ignoring case and the punctuation marks . , ! ? and breaking ties alphabetically.

  3. Exercise 3hard

    Write pair_sums(nums, target) that returns a set of unique pairs (smaller number first) that add up to target, in a single pass using a set. pair_sums([1, 5, 3, 3, 7, -1], 6) should give {(1, 5), (3, 3), (-1, 7)}.

Check yourself

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

Feel confident about this topic?

Frequently asked questions

Where can I find more beginner Python exercises?
Exercism's free Python track and the easy problems on sites like LeetCode or Codewars are good next steps. Solve them in your own editor with asserts first, then compare with other solutions.
How long should I struggle before looking at the answer?
About 15 to 20 minutes of real effort. Then read only a hint, and solve the problem again from scratch a day or two later so it sticks.
Should I use Counter and defaultdict or plain dicts?
Learn the plain-dict versions first so you understand what happens. In real code, Counter and defaultdict are clearer and leave less room for mistakes.
How do I know my solution is good enough?
It passes asserts for normal and edge cases, has a clear name, and you can explain every line. Speed only matters once the inputs get large.

Go deeper

ShareXLinkedInWhatsApp