Turn raw log lines into data
Real logs arrive as text lines. Three comprehensions pull out the levels, the users who had errors, and a count per day. sum(1 for ...) counts how many items pass a test.
A comprehension builds a new list, dictionary or set from another collection in one readable line: what to produce, where to take items from, and an optional filter. It replaces the common loop-and-append pattern, as long as it stays short enough to read at a glance.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 6 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Make a list of the cubes of 1 to 5 using a comprehension and range.
Given words = ["sun", "moon", "star", "sky"], build a list of the words that start with "s", in upper case.
Given prices = {"pen": 10, "book": 80, "bag": 500}, build a new dictionary with every price increased by 10 percent (use price * 1.1 and round(..., 2)).
Explain it without notes
Rewrite a loop that appends squares of even numbers as a comprehension, and explain how to read it.
What is the difference between [n for n in nums if n > 2] and [n if n > 2 else 0 for n in nums]?
How does the order of two for clauses in a comprehension work?
Is the loop variable of a comprehension visible afterwards?
What does funcs = [lambda: i for i in range(3)] give when you call each function, and why?
Expected output
levels: ['INFO', 'ERROR', 'INFO', 'ERROR', 'WARN']
users with errors: ['asha', 'ravi']
lines per day: {'2026-03-01': 2, '2026-03-02': 3}