Difference between List comprehension and dict comprehension

August 28, 2025   8 Min Read 12

List Comprehension

  • A list comprehension is a concise way to create a new list by applying an expression to each item in an iterable.

Syntax


[expression for item in iterable if condition]

Example:


nums = [1, 2, 3, 4, 5]
squares = [n**2 for n in nums]
print(squares)  # [1, 4, 9, 16, 25]

Dict Comprehension

  • A dictionary comprehension is a concise way to create dictionaries using expressions.

Syntax


{key_expression: value_expression for item in iterable if condition}

Example:


nums = [1, 2, 3, 4, 5]
square_map = {n: n**2 for n in nums}
print(square_map)  # {1:1, 2: 4, 3: 9, 4: 16, 5: 25}

Key Differences

FeatureList comprehensionDict Comprehension
Output TypeList([])Dictionary([])
Elements ProducedSingle valuesKey:Value pairs
Syntax[expr for item in iterable]{key: value for item in iterable}
Use CasesTransform sequence into listMap relationships (key → value)

Conditional Example

List comprehension with condition:


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

Dict comprehension with condition:


even_map = {n: n**2 for n in range(10) if n % 2 == 0}
print(even_map)  # {0: 0, 2: 4, 4: 16, 6: 36, 8: 64}

Performance & Real-life Use Cases

Performance

  • Both are faster than normal loops because they are implemented in C internally.
  • But dict comprehension can be slightly heavier since it manages hashing for keys.

Real-life Examples

1.  List Comprehension → Flatten Matrix


matrix = [[1, 2], [3, 4], [5, 6]]
flatten = [num for row in matrix for num in row]]
print(flatten)  # [1, 2, 3, 4, 5, 6]

2. Dict Comprehension → Word Count


sentence = "python interview preparation with python"
word_count = {word: sentence.split().count(word) for word in set(sentence.split())}
print(word_count)

# {'preparation': 1, 'python': 2, 'with': 1, 'interview': 1}

3. Filter Dictionary


prices = {"apple": 50, "banana": 20, "mango": 60}
expensive = {k: v for k, v in prices.items() if v > 30}
print(expensive)  # {'apple': 50, 'mango': 60}

🏆 Interview-ready Answer

A list comprehension produces a list using a singe expression, while a dict comprehension produces a dictionary with key-value pairs.

The syntax differs slightly:

  • "List: [expr for item in iterable if condition]"
  • "Dict: {key: value for item in iterable if condition}"

List comprehensions are best for transforming sequences, while dict comprehensions are ideal for mapping relationships or filtering dictionaries. Both are faster and more Pythonic than using loops.

Leave a Reply