Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Python
  • Python for AI: The Five Tools You Actually Need
  • Thinking Like a Python Architect in an AI-First World
  • Your First Python Program: print, Comments, sep and end
  • Set Up PyCharm for Python: Install, First Project and First Run
  • Run a Python File and Read the Error: Tracebacks in Three Steps
  • Python Data Types, Variables and Strings: Indexing, Slicing and f-strings
  • Python Operators: Arithmetic, Comparison, Logical, Membership, Identity and Precedence
  • Python Conditionals and Loops: if/elif/else, for, while, break and continue
  • Looping Over Real Data in Python: Dicts, Lists of Dicts, enumerate and zip
  • Checking AI-Written Python Code: A Six-Step Habit That Finds Three Hidden Faults
  • Python Basics Practice: Report Card, Shopping Cart and Password Checker from a Prompt
  • Python Functions: Parameters, Return, Scope (LEGB), *args and **kwargs
  • Type Hints on Python Functions: Parameters, Returns, None and Collections
  • Python lambda, map, filter, Modules and Packages (with pip and venv)
  • Python Functions Practice: Bonus Calculator, Product Pipeline and a Math Package
  • Python Lists, Tuples, Sets and Dicts, Plus Type Hints on Variables
  • Python Comprehensions: List, Dict, Set and Generator Expressions, Read as Loops
  • Python Class Methods, Static Methods and Properties: What Each One Receives
  • Python Classes and Objects: __init__, self and PEP 8 Names
  • Python Inheritance and Polymorphism: super(), Overriding and Duck Typing
  • Python Multiple Inheritance, the MRO and Mixins
  • Python Encapsulation and Special Methods: Underscores, __str__, __add__ and __len__
  • Python Composition, Abstract Classes and Dataclasses
  • Python OOP Practice: Design a Bank, an Employee System and a Library
  • Set Up a Python AI Project with uv, VS Code and an API Key in .env
  • uv and pyproject.toml: Start, Add, Run and Rebuild a Python Project
  • Python try and except Basics: Catch an Error and Keep Going
  • Read and Write a File in Python: open, with, Modes and Encoding
  • Python Custom Exceptions and Advanced Error Handling: raise, raise from and the Call Stack
  • Python Logging and Debugging: Levels, Handlers, logger.exception and breakpoint()
  • Python File Modes, pathlib and Context Managers: x, r+, rb, Path and __enter__/__exit__
  • Python CSV, JSON and Large Files: csv, json, yield Pipelines, tomllib and pickle
  • Python Practice: Build a Log File Analyzer and a File Organizer
  • Python Project Structure for AI-Assisted Development: Packages, config.py and AGENTS.md
  • Regular Expressions in Python: search, findall, Groups and Greedy vs Lazy
  • Testing Python Code with pytest: assert, parametrize, fixtures and pytest.raises
  • Async Python: async def, await, asyncio.gather and the Blocking Trap
  • Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
  • One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask
  • Getting Started with Flask: Routes, Jinja2 Templates and WSGI in One Small App
  • Your First Flask App with uv: From an Empty Folder to a Page in Debug Mode
  • Flask Routes, Templates and url_for: Converters, Forms, Redirects and the Signed Session
  • Flask-SQLAlchemy Models and Flask-Migrate: From a Python Class to a Real Table
  • Building a Blog with an AI Coding Agent: Plan Mode, a Master Prompt and the First Review
  • Handing a Figma Design to an AI Agent: Compare the Files, Then Review the Change
  • Inside a Flask Blog: The App Factory, Blueprints, the Instance Folder and CORS Done Right
  • How a Request and a Login Flow Through a Flask Blog: Flask-Login, CSRF and the Signed Session
  • Testing a Flask Blog with pytest: A Test App from the Factory, Fixtures and the Test Client
  1. Blog
  2. /
  3. Python
  4. /
  5. Lists, Dicts and Sets

Python Comprehensions: List, Dict, Set and Generator Expressions, Read as Loops

A comprehension is a small loop folded into one line. Every form is shown beside the loop it replaces: lists, the if at the end versus if/else at the front, dicts, sets, two fors, generator expressions, and when to go back to a loop.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Lists, Dicts and Sets

What you will learn

  • Fold a for loop that appends into a list comprehension, and read one back as a loop
  • Tell an if at the end (a filter) from an if/else at the front (a choice of value)
  • Write dict and set comprehensions and two-for comprehensions such as flattening a grid
  • Use a generator expression inside sum, any and max, and know when a plain loop reads better

Before you start

  • Looping Over Real Data in Python
  • Python lambda, map, filter, Modules and Packages

AI tools write comprehensions all the time, so you need to read them. A comprehension is a small loop folded into a single line.

Say you need a tray of filled cups and you're explaining it to a friend. You could give steps: take an empty tray, pick up each cup from the shelf, fill it, put it on the tray. Or one sentence: a filled cup, for every cup on the shelf. Same tray. The sentence says what you want first and where it comes from after. The steps are the loop; the sentence is the comprehension.

The fold

numbers = [1, 2, 3, 4, 5]

squares = []
for n in numbers:
    squares.append(n * n)
print(squares)

squares = [n * n for n in numbers]
print(squares)
[1, 4, 9, 16, 25]
[1, 4, 9, 16, 25]
Folding a loop: the appended value n * n moves to the front, for n in numbers follows it, square brackets replace the empty list and append squares = [] for n in numbers: squares.append(n * n) [n * n for n in numbers] Read it: start at the for, then go back to the front. "For each n in numbers, give me n * n."
The value you appended slides to the front; the brackets replace the empty list and append.

n * n, the value you were appending, slides to the front. for n in numbers comes behind it and the colon drops off. Square brackets go around both and replace the empty list, and append falls away because the brackets already mean "build a list".

An if at the end is a gate

scores = [85, 42, 91, 67, 78]

passed = []
for s in scores:
    if s >= 70:
        passed.append(s)
print(passed)

passed = [s for s in scores if s >= 70]
print(passed)
[85, 91, 78]
[85, 91, 78]

The if slides to the end. It decides which items get in, which is why the new list can be shorter.

An if/else at the front is a choice

scores = [85, 42, 91, 67, 78]

labels = []
for s in scores:
    if s >= 70:
        labels.append("pass")
    else:
        labels.append("retry")
print(labels)

labels = ["pass" if s >= 70 else "retry" for s in scores]
print(labels)
['pass', 'retry', 'pass', 'retry', 'pass']
['pass', 'retry', 'pass', 'retry', 'pass']

Every score stays; only the label changes, so the whole choice slides to the front. Five scores in, five labels out. This one difference trips up a lot of people, so when you read a comprehension, first check where the if is sitting. At the end, it drops items. At the front with an else, it keeps every item and changes its value.

Dict comprehensions

names = ["maya", "ravi", "zoe"]

lengths = {}
for name in names:
    lengths[name] = len(name)
print(lengths)

lengths = {name: len(name) for name in names}
print(lengths)

prices = {"pen": 10, "book": 250, "bag": 900}
cheap = {k: v for k, v in prices.items() if v < 500}
print(cheap)
{'maya': 4, 'ravi': 4, 'zoe': 3}
{'maya': 4, 'ravi': 4, 'zoe': 3}
{'pen': 10, 'book': 250}

key: value goes at the front, inside curly braces; the colon tells you it's a dict. You'll often see it with .items(). Read it in order: for k and v in prices.items(), if v is under 500. The bag at 900 doesn't get through.

Set comprehensions

words = ["tea", "cup", "pot", "kettle", "tea"]

sizes = set()
for w in words:
    sizes.add(len(w))
print(sizes)

sizes = {len(w) for w in words}
print(sizes)
{3, 6}
{3, 6}

Curly braces with no colon give a set. Tea, cup and pot all give 3, and a set keeps one of each, so the threes land on the same spot. Reach for this when you want distinct values, and remember a set doesn't promise any order.

Two loops in one line

sizes = ["S", "M"]
colors = ["red", "blue"]

pairs = []
for size in sizes:
    for color in colors:
        pairs.append((size, color))
print(pairs)

pairs = [(s, c) for s in sizes for c in colors]
print(pairs)

grid = [[1, 2], [3, 4], [5, 6]]
flat = [n for row in grid for n in row]
print(flat)
[('S', 'red'), ('S', 'blue'), ('M', 'red'), ('M', 'blue')]
[('S', 'red'), ('S', 'blue'), ('M', 'red'), ('M', 'blue')]
[1, 2, 3, 4, 5, 6]

The two fors stay in the same order as the loop: outer first, then inner. That's the part people misread. The last line flattens a list of lists: for each row in the grid, for each n in that row. Two fors is about the limit; beyond that, a plain loop is kinder to whoever reads it.

Generator expressions

numbers = [1, 2, 3, 4, 5]

total = sum([n * n for n in numbers])
print(total)

total = sum(n * n for n in numbers)
print(total)

print(any(n > 4 for n in numbers))
print(max(len(w) for w in ["tea", "kettle", "cup"]))

lazy = (n * n for n in numbers)
print(type(lazy).__name__)
print(list(lazy))
55
55
True
6
generator
[1, 4, 9, 16, 25]

When you only need one answer, drop the square brackets. It still gives 55, but no list gets built; each value joins the total and is gone. This is a generator expression, and it fits well inside sum, any and max. With round brackets and a name, its type is generator: nothing has been worked out yet, until list asks for the values. Square brackets give you the whole list now; round brackets give you values when they're asked for.

map and filter, side by side

numbers = [1, 2, 3, 4, 5, 6]

by_map = list(map(lambda n: n * 2, numbers))
by_comp = [n * 2 for n in numbers]
print(by_map == by_comp)

by_filter = list(filter(lambda n: n % 2 == 0, numbers))
by_comp = [n for n in numbers if n % 2 == 0]
print(by_filter == by_comp)
print(by_comp)
True
True
[2, 4, 6]

map is the front of the comprehension and filter is the if at the end. You'll see both in AI code, but many Python developers prefer the comprehension, since there's no lambda to read. (More on these two in lambda, map and filter.)

The loop variable stays inside

numbers = [1, 2, 3]
doubled = [n * 2 for n in numbers]
print(doubled)
print(n)
[2, 4, 6]
Traceback (most recent call last):
  File "S02L02_1_Comprehensions\comprehension_scope.py", line 4, in <module>
    print(n)
          ^
NameError: name 'n' is not defined

The n in a comprehension belongs to that comprehension. Unlike a for loop, you can't use it after the line ends.

When a loop reads better

orders = [
    {"item": "pen", "qty": 3, "paid": True},
    {"item": "book", "qty": 0, "paid": True},
    {"item": "bag", "qty": 2, "paid": False},
]

squeezed = [o["item"].upper() if o["qty"] > 0 else "NONE"
            for o in orders if o["paid"]]
print(squeezed)

result = []
for o in orders:
    if not o["paid"]:
        continue
    if o["qty"] > 0:
        result.append(o["item"].upper())
    else:
        result.append("NONE")
print(result)
print(squeezed == result)
['PEN', 'NONE']
['PEN', 'NONE']
True

The squeezed line has an if/else at the front, a for, and another if at the end. Try reading it out loud. The plain loop gives the same result and is far easier to check. A good rule: one for and one if, use a comprehension. More than that, or anything other than building a collection, use a loop. And if an AI tool hands you a line you can't read, prompt it: "Rewrite this as a plain loop."

Quick recap

BracketsYou getExample
[ ]list[n * n for n in numbers]
{k: v}dict{name: len(name) for name in names}
{ }set{len(w) for w in words}
( )generatorsum(n * n for n in numbers)
if at the endfewer items[s for s in scores if s >= 70]
if/else at the frontsame count, new values["pass" if s >= 70 else "retry" for s in scores]

Try it yourself

Take the loop that collected the passed students in Looping over real data and write it as a comprehension. You should get ['Maya', 'Zoe'] both ways.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in Python · 17 of 48

Previous
Python Lists, Tuples, Sets and Dicts, Plus Type Hints on Variables
Next post
Python Class Methods, Static Methods and Properties: What Each One Receives

Related course on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Related posts

Python Lists, Tuples, Sets and Dicts, Plus Type Hints on Variables

A shopping list, a map pin, a stamp album and a contact book: Python's four collections with real output, the KeyError and empty-set traps, and type hints that label a variable without locking it.

On this page

  • The fold
  • An if at the end is a gate
  • An if/else at the front is a choice
  • Dict comprehensions
  • Set comprehensions
  • Two loops in one line
  • Generator expressions
  • map and filter, side by side
  • The loop variable stays inside
  • When a loop reads better
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.