✦ Python Intermediate & OOP Intermediate Python

L2 · Concept 01 · Advanced Python Techniques

Build collections
from one clear idea.

Comprehensions turn a familiar loop into a focused way to build a new list, set, or dictionary.

Learning goalUse list, set, and dictionary comprehensions to transform or filter collection data, and recognize when a regular for loop is clearer.
01 Learn02 Try03 Predict

Learning as a guest

Learning as a guest? Save your progress!

Create a free account to learn with Sloby AI, check your understanding, and track your progress.

The entire platform is free throughout 2026. Foundations stays free forever.

A comprehension builds a collection while it loops.

A regular for loop is often the clearest place to start. When the loop has one focused job—build a collection—a comprehension can express the same idea in one readable line.

numbers = [1, 2, 3, 4]

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

# The same focused transformation:
squares = [number * number for number in numbers]

Both versions visit each number and add its square to a new list. The comprehension keeps the result expression, the loop variable, and the source data together.

print(squares) # [1, 4, 9, 16]

The brackets choose the result type: [] makes a list, {} with one expression makes a set, and {key: value} makes a dictionary.

↳

Keep readability first: Use a regular loop when the work needs several steps, multiple side effects, or a long nested condition. A short comprehension should make code easier—not harder—to read.

Practical examples
names = ["ana", "marko", "jelena"]
uppercase_names = [name.upper() for name in names]

words = ["Python", "practice", "Python"]
initials = {word[0].lower() for word in words}

scores = {"Ana": 82, "Marko": 45, "Jelena": 91}
passed_scores = {name: score for name, score in scores.items() if score >= 60}

The first line transforms every name into a list. The second keeps unique initials in a set. The last one keeps only passing name-and-score pairs in a dictionary.

List comprehension — transform every item
prices = [100, 250, 80]
with_tax = [price * 1.2 for price in prices]

The expression before for is the value added for each price.

Set comprehension — keep unique results
cities = ["Novi Sad", "Niš", "Novi Sad"]
lengths = {len(city) for city in cities}

A set removes duplicate results. Do not use it when the displayed order matters.

Dictionary comprehension — create key-value pairs
words = ["python", "code"]
word_lengths = {word: len(word) for word in words}

Put the key and value before for. Repeated keys replace an earlier value, so choose keys carefully.

Read a comprehension from right to left

  1. 1. Start with the sourcefor name, score in scores.items() supplies one name-and-score pair at a time.
  2. 2. Choose the result expressionname, score * 1.2, or name: score describes what one iteration contributes.
  3. 3. Add an optional filterif score >= 60 keeps only iterations that meet the condition; it does not run an else branch.
  4. 4. Check the outer bracketsSquare brackets create a list, curly brackets create a set, and key: value inside curly brackets creates a dictionary.

Common mistakes

  • Choosing the wrong collectionUse a list for ordered results, a set for unique values, and a dictionary when each value needs a meaningful key.
  • Expecting a set orderSets are useful for uniqueness, not for a predictable display order.
  • Accidentally repeating a dictionary keyA later value for the same key replaces an earlier one.
  • Hiding too much work in one lineIf you need to explain the line several times, prefer a regular loop with named intermediate values.

Python Playground

Loading Python runtime…

Change the source data, result expression, or filter. Predict the new collection before you run the code.

comprehensions.pyPython
OutputWaiting for Python
The browser runtime is loading. You can still edit the example code.

Pyodide runs Python in a browser Web Worker. It is stopped and restarted if code keeps running. Browser execution is not a complete security boundary; do not enter secrets or rely on it for untrusted code isolation.

What will this program print?

Trace the filter first. Only even numbers reach the expression before for.

numbers = [1, 2, 3, 4, 5]
doubled_evens = [number * 2 for number in numbers if number % 2 == 0]

print(doubled_evens)
Choose the output

Practice independently

Mini Challenge — Passing scores

Try this yourself before asking for a hint. You already know every building block you need.

Your goalBuild a list of passing student names, a dictionary of their scores, and—if you want an extra challenge—a set of unique scores.

passing_scores_challenge.py

Optional hints
  • Use scores.items() when you need a name and its score together.
  • The filter goes at the end: ... for name, score in scores.items() if score >= 60.
Ask Sloby for a hint
Sloby, the Python AI Tutor mascot

Your learning mentor

Sign in to ask Sloby

Create a free account or sign in to get AI guidance while you learn.

Sign in to check your understanding

Create a free account or sign in to receive AI feedback and save your learning progress.

Python AI Tutor · Learn by understanding, not just by running code.