Iterating Through Collections
Iterating Tuples Lists Dictionaries While Loop Exercises
💻 Exercises: Iterating Through Tuples, Lists, and Dictionaries with a While Loop
Ten exercises to practise everything from this lesson — index tracking, early-exit searches, in-place mutation, and building up a result collection one while-loop iteration at a time. Every problem here can technically be solved faster with a for loop or a built-in — that's not the point today. The point is building the muscle memory for manually tracking position, condition, and advance, since that's what makes a while loop the right tool once you hit a problem a for loop genuinely can't express (like this lesson's sentinel-controlled input example).
Exercise 1: Dedupe a List, Preserving Order
This lesson's case study deduplicated a tuple. Do the same thing for a list, using only while loops (no for, no dict.fromkeys(), no set()): given words_list = ["who", "why", "when", "who", "when", "what", "where", "whom", "who", "when", "who"], build a new list with the same words in the same order, duplicates removed.
Goal: Confirm the nested-while search-and-flag pattern works the same way on a mutable list, and that .append() (unlike tuple concatenation) is the natural way to grow the result here.
Exercise 2: Reverse a List In Place
Given numbers = [10, 20, 30, 40, 50, 60], reverse it in place (don't create a new list, don't use .reverse() or slicing) using a single while loop that swaps elements from both ends moving toward the middle.
Goal: Practise the "two pointers moving toward each other" pattern — a classic while-loop shape that a simple for i in range(len(x)) loop doesn't fit as naturally.
Exercise 3: Count Occurrences with a While Loop
Given fruits = ["apple", "pear", "apple", "banana", "pear", "apple"], use a while loop (no collections.Counter) to build a dictionary mapping each fruit to how many times it appears: {"apple": 3, "pear": 2, "banana": 1}.
Goal: Practise the "check if a key already exists, then either initialise it or increment it" pattern — one of the most common real-world uses of a dictionary.
Exercise 4: Linear Search Through a Tuple
Write a while loop that searches colours = ("red", "green", "blue", "yellow", "purple") for a target value entered via input(), printing the index where it was found, or "Not found" if the loop finishes without a match.
Goal: Practise the exact inner-search shape from this lesson's case study, standalone — including correctly distinguishing "found at index 0" (which is falsy-looking but valid) from "not found at all."
Exercise 5: Merge Two Dictionaries by Hand
Given defaults = {"theme": "dark", "font_size": 12, "autosave": True} and overrides = {"font_size": 14, "language": "en"}, use a while loop over one dictionary's keys to build a merged dictionary where overrides wins on any shared key — without using | or .update().
Goal: Practise converting a dictionary's keys to something index-walkable (list(d.keys())) since a while loop can't walk a dictionary directly the way a for loop can.
Exercise 6: Find the First Duplicate, Then Stop
Given ids = [101, 205, 309, 205, 412, 309], use a while loop (with a nested search, like this lesson's case study) to find and print the first value that turns out to be a duplicate, then stop scanning immediately — don't check the rest of the list once it's found.
Goal: Practise using break (in both the inner and outer loop) as a genuine early-exit optimisation, not just a way to leave a loop once its job is already done.
Exercise 7: Remove All Occurrences of a Value
Given numbers = [1, 2, 3, 2, 4, 2, 5], use a while loop to remove every occurrence of 2, leaving [1, 3, 4, 5]. Do not use list.remove() in a way that skips an element — think carefully about what happens to the indices after the one you just removed.
Goal: Confront the single most common real-world while-loop bug: modifying a list's length while walking it by index, and either skipping an element or re-checking one twice as a result.
Exercise 8: Running Totals from a List of Tuples
Given transactions = [("food", 12.50), ("transport", 3.20), ("food", 8.00), ("entertainment", 15.00), ("transport", 2.80)], use a while loop to build a dictionary of total spend per category: {"food": 20.50, "transport": 6.00, "entertainment": 15.00}.
Goal: Combine tuple unpacking with the "initialise-or-accumulate" dictionary pattern from Exercise 3, walking a list of tuples by index rather than with a for ... in unpacking loop.
Exercise 9: Invert a Dictionary
Given student_ids = {"Alice": 1001, "Bob": 1002, "Cleo": 1003, "Dev": 1001}, use a while loop to build a new dictionary with keys and values swapped. Notice that "Alice" and "Dev" share the same ID — decide what your inverted dictionary should do about that, and make sure your code does it deliberately rather than by accident.
Goal: Practise recognising a genuine edge case (a collision when inverting) rather than assuming every dictionary can be safely inverted one-to-one.
Exercise 10: Zip Two Lists into a Dictionary, Manually
Given keys = ["name", "age", "city"] and values = ["Priya", 29, "Leeds"], use a single while loop to combine them into {"name": "Priya", "age": 29, "city": "Leeds"} — without using the built-in zip() function or dict(zip(...)).
Goal: Practise walking two sequences in parallel with one shared index — and think about what your loop should do if keys and values turn out to be different lengths.