Open In App

Python Comprehensions Interview Questions

Last Updated : 26 Aug, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python, comprehensions are a concise way to create new sequences (like lists, sets, or dictionaries) from existing iterables. They combine a loop and an expression into a single readable line.

1. What is List Comprehension? Give an Example.

List comprehension is a way to create lists using a concise syntax. It allows us to generate a new list by applying an expression to each item in an existing iterable (such as a list or range). This helps us to write cleaner, more readable code compared to traditional looping techniques.

For example, if we have a list of integers and want to create a new list containing the square of each element, we can easily achieve this using list comprehension.

Python
a = [2,3,4,5]
res = [val ** 2 for val in a]
print(res)

Output
[4, 9, 16, 25]

2. What is Dictionary Comprehension? Give an Example

Dictionary Comprehension is a concise way to create dictionaries in Python using a single expression similar to list comprehension.

Python
keys = ['a','b','c','d','e']
vals = [1,2,3,4,5]  

# this line shows dict comprehension here  
d = { k:v for (k,v) in zip(keys, vals)}  

# We can use below too
# d = dict(zip(keys, values))  

print (d)

Output
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}

3. Is Tuple Comprehension possible in Python? If yes, how and if not why?

Tuple comprehensions are not directly supported. Python's existing features like generator expressions and the tuple() function provide flexible alternatives for creating tuples from iterable data.

(i for i in (1, 2, 3))

Tuple comprehension is not possible in Python because it will end up in a generator, not a tuple comprehension.

4. How can comprehensions and slicing be combined?

Python Slicing is a string operation for extracting a part of the string, or some part of a list. With this operator, one can specify where to start the slicing, where to end and specify the step. List slicing returns a new list from the existing list.

Syntax:

substring = s[start : end : step]

5. Explain set comprehension in Python with a filtering condition.

Set comprehension creates a set using a single line of code. Like lists, but ensures uniqueness.

Syntax:

{expression for item in iterable if condition}

Example:

Python
s = {x for x in range(10) if x % 2 == 0}
# Output: {0, 2, 4, 6, 8}

print(s)

Output
{0, 2, 4, 6, 8}

Set comprehension is helpful for:

  • Filtering unique values
  • Optimizing memory
  • Avoiding duplicates in data

6. What are nested comprehensions? Explain with a matrix-flattening example.

Nested comprehensions are comprehensions inside another comprehension, commonly used to handle nested iterables like lists of lists. They allow you to process multi-dimensional data in a single line.

Example: Flatten a 2D list

Python
m1 = [[1, 2], [3, 4], [5, 6]]
m2 = [num for row in m1 for num in row]  # flattend matrix
# Output: [1, 2, 3, 4, 5, 6]
print(m2)

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

7. How can you transpose a matrix using a list comprehension?

You can use nested comprehension with zip(*matrix) to swap rows and columns.

Python
m1 = [[1, 2, 3], [4, 5, 6]]
m2 = [[row[i] for row in m1] for i in range(len(m1[0]))]
print(m2)# transposed matrix
# OR: using zip
m3 = [list(col) for col in zip(*m1)]
print(m3)

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

8. Use dictionary comprehension to invert a dictionary with unique values. What happens when values are not unique?

Inverting maps keys to values, but if values are not unique, keys will be lost due to overwriting.

Python
d = {'a': 1, 'b': 2, 'c': 3}
i = {v: k for k, v in d.items()}  # inverter dictionary
# Duplicate values would cause loss
print(i)

Output
{1: 'a', 2: 'b', 3: 'c'}

9. Generate all Pythagorean triplets below 30 using list comprehension. Why is this approach better than nested loops?

A triple (a, b, c) is Pythagorean if a² + b² = c². List comprehension simplifies filtering and improves readability.

Python
t = [(a, b, c)
           for a in range(1, 30)
           for b in range(a, 30)
           for c in range(b, 30)
           if a**2 + b**2 == c**2]
print(t)

Output
[(3, 4, 5), (5, 12, 13), (6, 8, 10), (7, 24, 25), (8, 15, 17), (9, 12, 15), (10, 24, 26), (12, 16, 20), (15, 20, 25), (20, 21, 29)]

10. Explain how generator comprehensions differ from list comprehensions in memory usage and performance.

Generator comprehensions are similar in syntax to list comprehensions but use parentheses () instead of brackets []. The key difference is that generators produce items one at a time on demand, rather than storing the entire sequence in memory.

List comprehensions generate all values at once, using more memory. Generators yield items one by one, saving memory.

Python
gen = (x**2 for x in range(10))
for val in gen:
    print(val)  # Does not consume memory like a list

11. Create a dict comprehension that maps characters in a string to their frequencies. Explain time complexity.

Iterating over the string and building frequency count in one line is O(n).

Python
s = "mississippi"
freq = {char: 0 for char in set(s)}
for char in s:
    freq[char] += 1
print(freq)

Output
{'i': 4, 's': 4, 'p': 2, 'm': 1}

12. Use list comprehension to generate prime numbers under 50. Why is this approach not efficient for large n?

Using trial division in comprehension has O(n√n) time, not suitable for large ranges.

Python
p = [x for x in range(2, 50) if all(x % y != 0 for y in range(2, int(x**0.5)+1))]
print(p)

Output
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]

13. Generate all substrings of a string using list comprehension. Explain the constraints and complexity.

Use double iteration over string indices. Time: O(n²), Space: O(n²).

Python
s = "abc"
ss = [s[i:j] for i in range(len(s)) for j in range(i+1, len(s)+1)]  # substring
print(ss)

Output
['a', 'ab', 'abc', 'b', 'bc', 'c']

14. Use set comprehension to find all unique words of a sentence ignoring case.

Set removes duplicates, and using .lower() ensures case insensitivity.

Python
s = "The quick Brown fox the Quick brown"
u = {word.lower() for word in s.split()}
print(u)

Output
{'the', 'quick', 'fox', 'brown'}

15. Write a comprehension to flatten a list of dicts into one dict (non-conflicting keys).

This works only if keys are unique across dicts.

Python
ld = [{'a': 1}, {'b': 2}, {'c': 3}]
m = {k: v for d in ld for k, v in d.items()}
print(m)

Output
{'a': 1, 'b': 2, 'c': 3}

16. Write a comprehension that generates a Pascal’s triangle row-wise. Why is comprehension unsuitable beyond row 10?

It becomes computationally expensive and unreadable.

Python
n = 5
t = []    # empty list to store rows of triangle

for r in range(n):
    row = [1 if i == 0 or i == r else t[r-1][i-1] + t[r-1][i] for i in range(r+1)]
    t.append(row)

# Print the triangle
for row in t:
    print(row)

Output
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]

17. Can a list comprehension modify a global variable? Justify with example.

Yes, but it’s bad practice. Comprehensions create local scope for iteration variables.

Python
c = 0
[c := c + 1 for _ in range(5)]
print(c)  # Output: 5 (Python 3.8+ with walrus operator)

Output
5

Note: Before Python 3.8, this wouldn’t work because assignment expressions weren’t allowed in comprehensions.

18. Is it possible to generate a comprehension dynamically from user input? Explain risks.

Yes using eval, but it's dangerous due to code injection risk.

Python
s = "x**2 for x in range(5)"
code = eval(f"[{s}]")  # risky
print(code)

Output
[0, 1, 4, 9, 16]

Article Tags :