Skip to content
Learn Netverks

Lesson

Step 14/36 39% through track

comprehensions

Comprehensions

Last reviewed May 28, 2026 Content v20260528
Track mode
server_script
Means
Server runner
Reading
~1 min
Level
beginner

This lesson

This lesson teaches Comprehensions: the syntax, patterns, and safety habits you need before advancing in Python.

List and dict comprehensions are idiomatic Python—readable one-liners beat manual loops in reviews.

You will apply Comprehensions in contexts like: Scripts, Django/FastAPI apps, notebooks, and glue code between systems.

Write Python 3 in the editor and click Run on server—the dev runner executes your script with print() for output; stdlib only in playground snippets (LEARNING_RUNNER_ENABLED=true).

When you can explain the previous lesson's ideas without copying starter code.

Comprehensions build lists, dicts, or sets concisely from iterables—Pythonic alternative to map/filter loops, similar spirit to LINQ in C#.

List and dict comprehensions

squares = [n * n for n in range(5)]
evens = [n for n in range(10) if n % 2 == 0]
word_len = {w: len(w) for w in ["hi", "hello"]}

Set comprehensions

unique_lengths = {len(w) for w in ["hi", "hello", "hey"]}

Keep comprehensions readable—nested or long conditions belong in regular loops for clarity.

Important interview questions and answers

  1. Q: Comprehension vs map?
    A: Both transform iterables; comprehensions are often clearer; map accepts callables lazily in Python 3.
  2. Q: Generator expression?
    A: (x for x in iterable) yields lazily—memory efficient for large streams.

Self-check

  1. Write a comprehension for squares 0–4.
  2. What brackets build a dict comprehension?

Tip: Keep comprehensions readable—two nested loops often belong in a regular for loop.

Interview prep

List vs generator expression?

List builds in memory; generator (x for x in ...) yields lazily—better for large streams.

When not use comprehension?

Nested complex logic—plain loops improve readability for teammates.

Interview tip Lesson completion confidence

Can you explain this lesson in 30 seconds without reading notes?

Not saved yet.

Playground

Runs on the configured server runner (dev: npm run runner with LEARNING_RUNNER_ENABLED=true). Output appears below the editor.

Check yourself

Multiple choice — immediate feedback.

Discussion

Past discussion is visible to everyone. Only logged-in users can post comments and replies.

Starter discussion topics

  • List comp read?
  • Dict comp when?

Sign up or log in to post comments and sync lesson progress across devices.

No discussion yet. Be the first to ask a question.

Jump