Skip to content
LakeBench
ProblemsCommunityPricing
Sign inStart practicing
Back
  1. Home
  2. Interview prep
  3. List comprehension

Python · Collections & Basics

List comprehension

Easypython-03
list-comprehensionsyntaxcollections

Question

What is a list comprehension, and when would you use one?

Solution

A list comprehension builds a new list in one expression by transforming and/or filtering items from an iterable.

Form

[expression for item in iterable if condition]

Compared with a manual for loop plus append, comprehensions are usually shorter and clearer for simple transforms. Prefer a normal loop when the body is complex, has side effects, or needs early break/return.

# Classic loop
squares = []
for n in range(5):
    squares.append(n * n)

# Same idea as a comprehension
squares = [n * n for n in range(5)]
# [0, 1, 4, 9, 16]

# With a filter
evens = [n for n in range(10) if n % 2 == 0]
# [0, 2, 4, 6, 8]

# Nested: flatten a matrix
matrix = [[1, 2], [3, 4]]
flat = [x for row in matrix for x in row]
# [1, 2, 3, 4]

# Related: dict and set comprehensions
word_lens = {w: len(w) for w in ["sql", "spark"]}
unique = {c.lower() for c in "AaBb"}

Interview tip: Mention readability limits. Comprehensions are not "always better"; they are best for simple map/filter patterns.

🎯 Put this concept into practice

Solidify this answer with real hands-on interview drills in the browser studio.

Open related drill →
PreviousNext