Search⌘ K
AI Features

Nested and Conditional Comprehensions

Explore how to create concise and powerful Python comprehensions using filtering conditions, conditional expressions, and nested loops. Understand when to flatten lists, generate combinations, or apply conditional logic to manipulate complex data structures effectively. Learn to balance readability with compact code for maintainable programming.

In the previous lessons, we used comprehensions to transform data in a simple one-to-one mapping. However, real-world data is rarely that clean. Often, we need to extract specific items from a noisy dataset, label values based on rules, or flatten multi-layered lists into a single sequence. Python allows us to embed this logic directly into comprehensions, turning multiple lines of control flow into expressive, single-line summaries. While this power makes code concise, it requires a clear understanding of syntax order to ensure we control exactly what gets built.

Filtering with conditional clauses with if

The most common enhancement to comprehension is filtering. We often want to process a list but exclude items that do not meet specific criteria. In a standard loop, we would write an if statement inside the loop block. In a comprehension, we place the if clause immediately after the for loop it governs.

This clause acts as a gatekeeper. The expression at the start of the comprehension only runs for items where the condition is True.

Python 3.14.0
# A list of server response times in milliseconds
response_times = [120, 45, 300, 25, 600, 90]
# We want only the "slow" responses (greater than 100ms)
slow_responses = [t for t in response_times if t > 100]
print(f"Original count: {len(response_times)}")
print(f"Slow responses: {slow_responses}")
  • Line 2: This defines a list of integers representing milliseconds.

  • Line 5: We iterate through response_times, but instead of keeping every item, the if t > 100 clause checks each value first. Only the times that pass this check are allowed into the final list slow_responses. The others are ...