Home › Interview Questions › Can you provide Python code that uses nested list …

Can you provide Python code that uses nested list comprehensions to flatten a list of lists and filter even numbers?

🟡 Medium Coding Junior level
1Times asked
Sep 2026Last seen
Sep 2026First seen

💡 Model Answer

Below is a Python snippet that uses nested list comprehensions to flatten a list of lists and then filter even numbers: # Sample data: a list of lists matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # Flatten the matrix flat = [item for row in matrix for item in row] # Keep only even numbers evens = [x for x in flat if x % 2 == 0] print(evens) # Output: [2, 4, 6, 8] You can combine the two steps into a single comprehension: evens = [x for row in matrix for x in row if x % 2 == 0] This one‑liner is concise and efficient for moderate‑sized data. For very large matrices, consider using a generator expression or itertools.chain to avoid building intermediate lists. If you need to preserve the original structure while filtering, you can use a nested comprehension that returns sublists: filtered = [[x for x in row if x % 2 == 0] for row in matrix]. This keeps each row as a list of even numbers, resulting in [[2, 4], [6, 8]] for the example matrix. Using list comprehensions in this way keeps the code concise and readable, but remember that for very large matrices the memory overhead of creating intermediate lists can be significant. In such cases, a generator expression or itertools.compress may be more appropriate.

This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.

🎤 Get questions like this answered in real-time

Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.

Get Assisting AI — Starts at ₹500