FroquizFroquiz
HomeQuizzesSenior ChallengeGet CertifiedBlogAbout
Sign InStart Quiz
Sign InStart Quiz
Froquiz

The most comprehensive quiz platform for software engineers. Test yourself with 10000+ questions and advance your career.

LinkedIn

Platform

  • Start Quizzes
  • Topics
  • Blog
  • My Profile
  • Sign In

About

  • About Us
  • Contact

Legal

  • Privacy Policy
  • Terms of Service

Β© 2026 Froquiz. All rights reserved.Built with passion for technology
Blog & Articles

Python List Comprehensions: The Complete Guide with Examples

Master Python list comprehensions from basics to advanced patterns. Includes dict and set comprehensions, nested loops, filtering, and when NOT to use them.

Yusuf SeyitoğluMarch 11, 20262 views7 min read

Python List Comprehensions: The Complete Guide with Examples

List comprehensions are one of Python's most loved features β€” and one of the first things interviewers ask about. They let you build lists in a single, readable line instead of writing a for loop with .append().

This guide goes from the basics to advanced patterns, with real examples throughout.

The Basic Syntax

A list comprehension has this structure:

python
[expression for item in iterable]

Compare the two approaches:

python
# Traditional for loop squares = [] for n in range(10): squares.append(n ** 2) # List comprehension squares = [n ** 2 for n in range(10)] # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Same result, one line, more readable. That is the core idea.

Adding a Filter Condition

You can add an if clause to filter which items are included:

python
[expression for item in iterable if condition]
python
# Only even numbers evens = [n for n in range(20) if n % 2 == 0] # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] # Words longer than 4 characters words = ["cat", "elephant", "dog", "rhinoceros", "ox"] long_words = [w for w in words if len(w) > 4] # ["elephant", "rhinoceros"]

Applying a Function

The expression part can call any function:

python
# Uppercase all strings names = ["alice", "bob", "carol"] upper_names = [name.upper() for name in names] # ["ALICE", "BOB", "CAROL"] # Strip whitespace from each item raw = [" hello ", " world ", " python"] cleaned = [s.strip() for s in raw] # ["hello", "world", "python"] # Get file extensions files = ["report.pdf", "data.csv", "script.py", "image.png"] extensions = [f.split(".")[-1] for f in files] # ["pdf", "csv", "py", "png"]

if-else Inside a Comprehension

When you need to transform values differently based on a condition, put the if-else in the expression (not the filter position):

python
# if-else in expression β€” applies to every item result = [x if x > 0 else 0 for x in [-3, -1, 0, 2, 5]] # [0, 0, 0, 2, 5] # Label numbers as even or odd labels = ["even" if n % 2 == 0 else "odd" for n in range(6)] # ["even", "odd", "even", "odd", "even", "odd"]

Common confusion: if at the end filters items (some items excluded). if-else in the expression transforms items (all items kept, different values applied).

Nested List Comprehensions

You can nest comprehensions for multi-dimensional data:

python
# Flatten a 2D list matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] flat = [num for row in matrix for num in row] # [1, 2, 3, 4, 5, 6, 7, 8, 9] # All combinations of two lists colors = ["red", "blue"] sizes = ["S", "M", "L"] combos = [f"{c}-{s}" for c in colors for s in sizes] # ["red-S", "red-M", "red-L", "blue-S", "blue-M", "blue-L"]

Read nested comprehensions left-to-right β€” the outer loop comes first, inner loop second.

Comprehensions with Dictionaries and Sets

The same pattern works for dictionaries and sets.

Dict comprehension

python
{key_expr: value_expr for item in iterable} # Square each number as a dict squares = {n: n ** 2 for n in range(6)} # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25} # Invert a dictionary original = {"a": 1, "b": 2, "c": 3} inverted = {v: k for k, v in original.items()} # {1: "a", 2: "b", 3: "c"} # Filter a dict by value prices = {"apple": 1.2, "banana": 0.5, "cherry": 3.0} expensive = {k: v for k, v in prices.items() if v > 1.0} # {"apple": 1.2, "cherry": 3.0}

Set comprehension

python
{expression for item in iterable} # Unique lengths of words words = ["hi", "hello", "hey", "howdy", "hi"] lengths = {len(w) for w in words} # {2, 5} β€” set, so duplicates removed automatically

Generator Expressions

Replace [] with () and you get a generator expression β€” it yields items one at a time instead of building the whole list in memory.

python
# List β€” builds everything in memory immediately total = sum([n ** 2 for n in range(1_000_000)]) # Generator β€” computes on demand, much lower memory total = sum(n ** 2 for n in range(1_000_000))

Use a generator when you only need to iterate once and the list is large. Use a list when you need indexing, multiple iterations, or the result stored.

When NOT to Use List Comprehensions

List comprehensions are not always the right tool.

Too complex β€” use a regular loop:

python
# Hard to read β€” split into a loop result = [ process(transform(item)) for item in data if item.is_valid() if item.category in allowed_categories ] # Easier to read as a loop result = [] for item in data: if item.is_valid() and item.category in allowed_categories: result.append(process(transform(item)))

Side effects β€” use a regular loop:

python
# Bad β€” comprehension for side effects [print(x) for x in items] # creates a pointless list # Good for x in items: print(x)

Rule of thumb: If it fits comfortably on one line and reads naturally in English ("give me X for each Y where Z"), a comprehension is great. If you need to explain it, use a loop.

Common Interview Questions

Q: What is the difference between a list comprehension and a generator expression?

A list comprehension ([...]) creates the full list in memory immediately. A generator expression ((...)) produces values lazily one at a time, using far less memory.

Q: Can you use list comprehensions with multiple conditions?

Yes β€” chain if clauses:

python
result = [x for x in range(50) if x % 2 == 0 if x % 3 == 0] # Multiples of both 2 and 3: [0, 6, 12, 18, 24, 30, 36, 42, 48]

Q: How do you flatten a nested list?

python
nested = [[1, 2], [3, 4], [5, 6]] flat = [x for sublist in nested for x in sublist]

Practice Python on Froquiz

List comprehensions are just one piece of Python mastery. Test your Python knowledge on Froquiz β€” we cover comprehensions, decorators, generators, OOP, and much more across all difficulty levels.

Summary

  • Basic syntax: [expression for item in iterable]
  • Filter items: add if condition at the end
  • Transform all items: use
    code
    value_if_true if condition else value_if_false
    in the expression
  • Flatten or combine: nest multiple for clauses
  • Dict comprehension: {k: v for ...} β€” set comprehension: {expr for ...}
  • Generator expression: (expr for ...) β€” memory-efficient, lazy evaluation
  • Avoid comprehensions for complex logic or side effects β€” a regular loop is clearer

About Author

Yusuf Seyitoğlu

Author β†’

Other Posts

  • CSS Advanced Techniques: Custom Properties, Container Queries, Grid Masonry and Modern LayoutsMar 12
  • System Design Fundamentals: Scalability, Load Balancing, Caching and DatabasesMar 12
  • GraphQL Schema Design: Types, Resolvers, Mutations and Best PracticesMar 12
All Blogs