PYnative

Practice Coding

  • Python â–¼
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Coding Exercises â–¼
    • Python Exercises
    • C++ Exercises
    • C Programming Exercises
    • Java Exercises
    • C# Exercises
  • MCQsâ–¼
    • Python MCQ Quizzes
    • Java MCQ Quizzes
    • C++ MCQ Quizzes
  • Compilersâ–¼
    • Online Python Compiler
    • Online C Compiler
    • Online C++ Compiler
    • Online Java Compiler
    • Online C# Compiler
Home » Python » Basics » List, Dict, and Set Comprehensions in Python

List, Dict, and Set Comprehensions in Python

Updated on: December 4, 2026 | Leave a Comment

A comprehension is a short, readable way to build a new list, dictionary, or set from an existing iterable in a single expression. Instead of creating an empty list and calling append() inside a for loop, you describe the result you want: [n * n for n in numbers].

In this tutorial, you’ll learn the syntax of list, dictionary, and set comprehensions, how to filter and transform items, how nested comprehensions work, how generator expressions save memory, and when a regular loop is the better choice.

Key terms used in this article:

  • Comprehension: An expression that builds a collection from an iterable, such as [x * 2 for x in data].
  • Iterable: Anything you can loop over: a list, tuple, string, range, dictionary, set, file, and so on.
  • Expression: The part at the start of a comprehension that produces each new item.
  • Filter condition: An optional if clause that decides which items to keep.
  • Generator expression: A comprehension in parentheses that produces items lazily, one at a time.

Table of contents

  • Why use comprehensions?
  • List comprehensions
    • List comprehension syntax
    • Filtering with if
    • Transforming with if-else
    • Calling functions in a comprehension
  • Nested loops in comprehensions
    • Flattening a list of lists
    • Nested comprehensions: building a matrix
  • Dictionary comprehensions
    • Dictionary comprehension syntax
    • Transforming and filtering an existing dictionary
    • Swapping keys and values
    • Grouping and counting
  • Set comprehensions
  • Generator expressions
  • Using the walrus operator in comprehensions
  • Variable scope in comprehensions
  • Performance: comprehensions vs. loops
  • When not to use a comprehension
  • Comprehension cheat sheet
  • Common mistakes
  • Practice exercises
  • Summary

Why use comprehensions?

Here’s the same task, squaring the numbers from 1 to 5, written with a loop and with a list comprehension:

# With a for loop
squares = []
for n in range(1, 6):
    squares.append(n * n)
print(squares)

# With a list comprehension
squares = [n * n for n in range(1, 6)]
print(squares)Code language: Python (python)

Output:

[1, 4, 9, 16, 25]
[1, 4, 9, 16, 25]

Comprehensions are shorter, they make the purpose (building a new collection) obvious at a glance, and they usually run faster than the equivalent loop with append().

List comprehensions

List comprehension syntax

new_list = [expression for item in iterable]Code language: Python (python)

Read it from the middle: “for each item in iterable, evaluate expression, and collect the results in a list.”

names = ["jessa", "kelly", "emma"]
print([name.title() for name in names])

prices = [10, 25.5, 40]
print([round(p * 1.18, 2) for p in prices])

print([len(word) for word in "Python makes coding fun".split()])
print([ch for ch in "abc"])Code language: Python (python)

Output:

['Jessa', 'Kelly', 'Emma']
[11.8, 30.09, 47.2]
[6, 5, 6, 3]
['a', 'b', 'c']

Filtering with if

Add an if clause at the end to keep only the items that pass a test:

numbers = [3, 8, 15, 22, 7, 40]

evens = [n for n in numbers if n % 2 == 0]
print(evens)

big_squares = [n * n for n in numbers if n > 10]
print(big_squares)

words = ["apple", "", "banana", "  ", "cherry"]
print([w for w in words if w.strip()])Code language: Python (python)

Output:

[8, 22, 40]
[225, 484, 1600]
['apple', 'banana', 'cherry']

You can chain several if clauses. They work like and:

print([n for n in range(50) if n % 3 == 0 if n % 5 == 0])
print([n for n in range(50) if n % 3 == 0 and n % 5 == 0])Code language: Python (python)

Output:

[0, 15, 30, 45]
[0, 15, 30, 45]

Transforming with if-else

To change each item depending on a condition (instead of dropping items), put a conditional expression at the beginning:

numbers = [3, 8, 15, 22, 7]

labels = ["even" if n % 2 == 0 else "odd" for n in numbers]
print(labels)

capped = [n if n <= 10 else 10 for n in numbers]
print(capped)Code language: Python (python)

Output:

['odd', 'even', 'odd', 'even', 'odd']
[3, 8, 10, 10, 7]

Where does the if go? [x for x in data if condition] filters items, so the result can be shorter. [a if condition else b for x in data] transforms every item, so the result has the same length. An if at the end can’t have an else.

You can combine both forms:

scores = [45, 82, None, 67, 91, None]
results = ["pass" if s >= 50 else "fail" for s in scores if s is not None]
print(results)Code language: Python (python)

Output:

['fail', 'pass', 'pass', 'pass']

Calling functions in a comprehension

def celsius_to_fahrenheit(c):
    return round(c * 9 / 5 + 32, 1)

temps = [0, 21.5, 37, 100]
print([celsius_to_fahrenheit(t) for t in temps])

raw = [" 42", "7 ", " 19 "]
print([int(x) for x in raw])Code language: Python (python)

Output:

[32.0, 70.7, 98.6, 212.0]
[42, 7, 19]

Nested loops in comprehensions

A comprehension can have several for clauses. They run in the same order as nested for loops written out normally:

# Nested loops
pairs = []
for color in ["red", "blue"]:
    for size in ["S", "M"]:
        pairs.append((color, size))
print(pairs)

# Comprehension: same order of for clauses
pairs = [(color, size) for color in ["red", "blue"] for size in ["S", "M"]]
print(pairs)Code language: Python (python)

Output:

[('red', 'S'), ('red', 'M'), ('blue', 'S'), ('blue', 'M')]
[('red', 'S'), ('red', 'M'), ('blue', 'S'), ('blue', 'M')]

Flattening a list of lists

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [num for row in matrix for num in row]
print(flat)Code language: Python (python)

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9]

Read it as: “for each row in matrix, for each num in row, collect num.”

Nested comprehensions: building a matrix

A comprehension inside another comprehension’s expression creates nested lists:

table = [[row * col for col in range(1, 4)] for row in range(1, 4)]
for row in table:
    print(row)

matrix = [[1, 2, 3], [4, 5, 6]]
transposed = [[row[i] for row in matrix] for i in range(3)]
print(transposed)Code language: Python (python)

Output:

[1, 2, 3]
[2, 4, 6]
[3, 6, 9]
[[1, 4], [2, 5], [3, 6]]

The outer comprehension builds the rows, and the inner one builds the values in each row. For transposing, list(zip(*matrix)) is a shorter alternative.

Dictionary comprehensions

Dictionary comprehension syntax

new_dict = {key_expression: value_expression for item in iterable}Code language: Python (python)
names = ["jessa", "kelly", "emma"]
print({name: len(name) for name in names})

print({n: n ** 2 for n in range(1, 6)})

keys = ["name", "age", "city"]
values = ["Jessa", 28, "London"]
print({k: v for k, v in zip(keys, values)})Code language: Python (python)

Output:

{'jessa': 5, 'kelly': 5, 'emma': 4}
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
{'name': 'Jessa', 'age': 28, 'city': 'London'}

Transforming and filtering an existing dictionary

Loop over items() to work with both keys and values:

prices = {"apple": 1.2, "mango": 2.5, "banana": 0.5, "cherry": 3.0}

# Apply a 10% discount
print({fruit: round(price * 0.9, 2) for fruit, price in prices.items()})

# Keep only items costing more than $1
print({fruit: price for fruit, price in prices.items() if price > 1})

# Uppercase the keys
print({fruit.upper(): price for fruit, price in prices.items()})Code language: Python (python)

Output:

{'apple': 1.08, 'mango': 2.25, 'banana': 0.45, 'cherry': 2.7}
{'apple': 1.2, 'mango': 2.5, 'cherry': 3.0}
{'APPLE': 1.2, 'MANGO': 2.5, 'BANANA': 0.5, 'CHERRY': 3.0}

Swapping keys and values

codes = {"IN": "India", "FR": "France", "JP": "Japan"}
print({country: code for code, country in codes.items()})Code language: Python (python)

Output:

{'India': 'IN', 'France': 'FR', 'Japan': 'JP'}

If several keys share the same value, later items overwrite earlier ones, because dictionary keys must be unique.

Grouping and counting

words = ["apple", "avocado", "banana", "blueberry", "cherry"]

first_letters = {w[0] for w in words}
groups = {letter: [w for w in words if w[0] == letter] for letter in sorted(first_letters)}
print(groups)

text = "mississippi"
print({ch: text.count(ch) for ch in sorted(set(text))})Code language: Python (python)

Output:

{'a': ['apple', 'avocado'], 'b': ['banana', 'blueberry'], 'c': ['cherry']}
{'i': 4, 'm': 1, 'p': 2, 's': 4}

These examples are readable, but they scan the list once per key. For large data, collections.Counter and defaultdict are faster.

Set comprehensions

A set comprehension uses curly braces without a colon. The result is a set, so duplicates are removed automatically:

words = ["Apple", "apple", "BANANA", "banana", "Cherry"]
print(sorted({w.lower() for w in words}))

numbers = [1, -2, 3, -1, 2, -3]
print(sorted({abs(n) for n in numbers}))

emails = ["jessa@gmail.com", "kelly@yahoo.com", "emma@gmail.com"]
print(sorted({e.split("@")[1] for e in emails}))Code language: Python (python)

Output:

['apple', 'banana', 'cherry']
[1, 2, 3]
['gmail.com', 'yahoo.com']

Sets are unordered, so sorted() is used here to display the results in a predictable order.

Note that {} on its own creates an empty dictionary, not a set. Use set() for an empty set.

Generator expressions

Use parentheses instead of square brackets to create a generator expression. It produces items one at a time, only when they’re needed, instead of building a full list in memory:

import sys

squares_list = [n * n for n in range(1_000_000)]
squares_gen = (n * n for n in range(1_000_000))

print(sys.getsizeof(squares_list) > 1_000_000)
print(sys.getsizeof(squares_gen) < 1_000)
print(sum(squares_gen))Code language: Python (python)

Output:

True
True
333332833333500000

When a generator expression is the only argument of a function, you can drop the extra parentheses:

words = ["python", "comprehension", "is", "neat"]

print(sum(len(w) for w in words))
print(max(len(w) for w in words))
print(any(w.startswith("c") for w in words))
print(", ".join(w.upper() for w in words))Code language: Python (python)

Output:

25
13
True
PYTHON, COMPREHENSION, IS, NEAT

A generator can only be used once. After it’s exhausted, it produces nothing:

gen = (n for n in range(3))
print(list(gen))
print(list(gen))Code language: Python (python)

Output:

[0, 1, 2]
[]

There’s no tuple comprehension. To build a tuple, pass a generator expression to tuple(): tuple(n * 2 for n in range(3)).

Using the walrus operator in comprehensions

The assignment expression := (Python 3.8+) lets you compute a value once and use it in both the filter and the result:

def expensive(n):
    return n * n - 10

results = [y for n in range(6) if (y := expensive(n)) > 0]
print(results)Code language: Python (python)

Output:

[6, 15]

Without :=, you’d have to call expensive(n) twice.

Variable scope in comprehensions

The loop variable in a comprehension is local to the comprehension. It doesn’t leak into or overwrite the surrounding code:

x = "original"
squares = [x * x for x in range(3)]
print(x)Code language: Python (python)

Output:

original

Performance: comprehensions vs. loops

List comprehensions are usually faster than building a list with append() in a loop, because they avoid repeated method lookups:

import timeit

loop_code = """
result = []
for n in range(1000):
    result.append(n * 2)
"""
comp_code = "result = [n * 2 for n in range(1000)]"

loop_time = timeit.timeit(loop_code, number=2000)
comp_time = timeit.timeit(comp_code, number=2000)
print(f"Loop:          {loop_time:.3f} seconds")
print(f"Comprehension: {comp_time:.3f} seconds")Code language: Python (python)

Run it to compare on your own machine. The exact times depend on your computer and Python version, and the comprehension is usually the faster of the two. Still, choose comprehensions for readability first. The speed difference only matters in hot code paths.

When not to use a comprehension

Comprehensions are for building collections. Use a regular for loop when:

  • You only want side effects, such as printing or writing to a file. [print(x) for x in items] builds a useless list of None values.
  • The logic is complex. More than two for clauses, or long conditions, are hard to read. Split them into a loop or a helper function.
  • You need statements such as try/except, break, or multiple assignments.
# Too clever: hard to read
result = [(x, y) for x in range(4) if x % 2 == 0 for y in range(4) if y > x if (x + y) % 3 != 0]
print(result)

# Clearer: a loop with comments
result = []
for x in range(0, 4, 2):          # even x only
    for y in range(x + 1, 4):     # y greater than x
        if (x + y) % 3 != 0:
            result.append((x, y))
print(result)Code language: Python (python)

Output:

[(0, 1), (0, 2), (2, 3)]
[(0, 1), (0, 2), (2, 3)]

Comprehension cheat sheet

TypeSyntaxResult
List[x * 2 for x in data]list
List with filter[x for x in data if x > 0]list (possibly shorter)
List with if-else[x if x > 0 else 0 for x in data]list (same length)
Nested loops[x * y for x in a for y in b]list
Dictionary{k: v for k, v in pairs}dict
Set{x % 3 for x in data}set
Generator(x * 2 for x in data)generator (lazy)

Common mistakes

  • Putting else with a filter at the end. [x for x in data if x > 0 else 0] is a SyntaxError. Move the conditional expression to the front.
  • Reversing the order of nested for clauses. Write them in the same order as nested loops: outer loop first.
  • Using {} for an empty set. That’s an empty dictionary.
  • Reusing an exhausted generator. Convert it to a list if you need the items more than once.
  • Writing comprehensions just for side effects. Use a normal loop.

Practice exercises

Exercise 1: Create a list of all numbers from 1 to 30 that are divisible by 3 but not by 2.

print([n for n in range(1, 31) if n % 3 == 0 and n % 2 != 0])Code language: Python (python)

Output:

[3, 9, 15, 21, 27]

Exercise 2: Given a sentence, build a dictionary that maps each word to its length, skipping words shorter than 3 characters.

sentence = "Comprehensions in Python are a neat and fast tool"
print({w: len(w) for w in sentence.split() if len(w) >= 3})Code language: Python (python)

Output:

{'Comprehensions': 14, 'Python': 6, 'are': 3, 'neat': 4, 'and': 3, 'fast': 4, 'tool': 4}

Exercise 3: Flatten a list of lists and keep only the unique values, sorted.

data = [[3, 1, 2], [2, 4], [1, 5, 3]]
print(sorted({n for row in data for n in row}))Code language: Python (python)

Output:

[1, 2, 3, 4, 5]

Exercise 4: From a dictionary of students and scores, build a dictionary that maps each student to “pass” or “fail” (pass mark 50).

scores = {"Jessa": 72, "Kelly": 45, "Emma": 90}
print({name: "pass" if score >= 50 else "fail" for name, score in scores.items()})Code language: Python (python)

Output:

{'Jessa': 'pass', 'Kelly': 'fail', 'Emma': 'pass'}

Summary

  • A comprehension builds a new collection from an iterable in one readable expression.
  • List: [expr for x in data]. Dictionary: {k: v for x in data}. Set: {expr for x in data}.
  • An if at the end filters items. A conditional expression at the start transforms every item.
  • Several for clauses work like nested loops, in the same order.
  • Generator expressions, (expr for x in data), produce items lazily and save memory. Pass them directly to sum(), max(), any(), and join().
  • Use comprehensions to build collections, and regular loops for side effects or complex logic.

Also, See:

  • Python List Methods
  • Python Dictionary Methods
  • Python Comprehensions Exercises
  • Python for loop

Filed Under: Python, Python Basics

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Python Python Basics

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises
Java Exercises
C# Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

In: Python Python Basics
TweetF  sharein  shareP  Pin

  Python Tutorials

  • Get Started with Python
  • Python Statements
  • Python Comments
  • Python Keywords
  • Python Variables
  • Python Operators
  • Python Data Types
  • Python Casting
  • Python Control Flow statements
  • Python For Loop
  • Python While Loop
  • Python Break and Continue
  • Python Nested Loops
  • Python Input and Output
  • Python range function
  • Check user input is String or Number
  • Accept List as a input from user
  • Python Numbers
  • Python Lists
  • Python Tuples
  • Python Sets
  • Python Dictionaries
  • Python Functions
  • Python Modules
  • Python isinstance()
  • Python OOP
  • Python Inheritance
  • Python Exceptions
  • Python Exercise for Beginners
  • Python Quiz for Beginners

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

All Python Topics

  • Python Basics
  • Python Exercises
  • Python Quizzes
  • Python File Handling
  • Python Date and Time
  • Python OOP
  • Python Random
  • Python Regex
  • Python Pandas
  • Python Databases
  • Python MySQL
  • Python PostgreSQL
  • Python SQLite
  • Python JSON

About PYnative

PYnative.com is a platform built to help developers learn by doing. Solve coding exercises, take MCQs, and run code directly in built-in online compilers.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises
  • Java Exercises
  • C# Exercises

MCQ Quizzes

  • Python MCQs
  • Java MCQs
  • C++ MCQs

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com