← Back to libraryQuestion 195 of 468
🐍PythonIntermediate

List Comprehensions

📌 Definition:

A list comprehension builds a list in one readable expression: [expr for item in iterable if condition]. It replaces many explicit for-loops and is faster and more Pythonic.

📖 Detailed Explanation:

Instead of creating an empty list and appending in a loop, you write [x*2 for x in nums if x % 2 == 0]. The pattern generalizes to dict comprehensions ({k: v for ...}) and set comprehensions ({x for ...}). For large or lazy sequences, a generator expression (round brackets) avoids building the whole list in memory. Testers use comprehensions to extract fields from API results ([u['id'] for u in users]), filter datasets, and transform test data concisely. Keep them simple — deeply nested comprehensions hurt readability.

🔑 Key Points:
  • [expr for x in iterable if cond] — build lists concisely
  • Also dict/set comprehensions; () gives a lazy generator
  • Faster and cleaner than manual append loops
  • Avoid over-nesting — readability first
🌍 Real-World Example:

Extracting active user emails from an API response: emails = [u['email'] for u in response.json() if u['active']] — one line replaces a five-line loop.

🎯 Scenario-Based Interview Question:

Rewrite this as a comprehension: result = []\nfor u in users:\n if u['active']:\n result.append(u['name'])