Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 4.7 — List, Dict and Set Comprehensions
Python · Example 3 of 3

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.

01

Make a list of the cubes of 1 to 5 using a comprehension and range.

02

Given words = ["sun", "moon", "star", "sky"], build a list of the words that start with "s", in upper case.

03

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

01

Rewrite a loop that appends squares of even numbers as a comprehension, and explain how to read it.

02

What is the difference between [n for n in nums if n > 2] and [n if n > 2 else 0 for n in nums]?

03

How does the order of two for clauses in a comprehension work?

04

Is the loop variable of a comprehension visible afterwards?

05

What does funcs = [lambda: i for i in range(3)] give when you call each function, and why?

Turn raw log lines into data
Sign in to run this example in your browser.

Expected output

levels: ['INFO', 'ERROR', 'INFO', 'ERROR', 'WARN']
users with errors: ['asha', 'ravi']
lines per day: {'2026-03-01': 2, '2026-03-02': 3}