if/else in a list comprehension

Learn if/else in a list comprehension with practical examples, diagrams, and best practices. Covers python, list, if-statement development techniques with visual explanations.

Conditional Logic in Python List Comprehensions

Hero image for if/else in a list comprehension

Master the art of using 'if/else' statements within Python list comprehensions to create dynamic and concise lists.

Python list comprehensions offer a powerful and elegant way to create lists. They are often more readable and efficient than traditional for loops. A common requirement is to apply conditional logic during list creation, allowing you to include elements based on certain criteria or transform elements differently based on conditions. This article explores how to effectively use if and if/else statements within list comprehensions, providing clear examples and best practices.

Basic 'if' Condition for Filtering

The simplest form of conditional logic in a list comprehension is an if clause placed at the end of the comprehension. This acts as a filter, including only those items that satisfy the condition. Items that do not meet the condition are simply excluded from the new list.

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = [num for num in numbers if num % 2 == 0]
print(even_numbers)
# Output: [2, 4, 6, 8, 10]

Filtering even numbers using an 'if' condition

flowchart TD
    A[Start List Comprehension] --> B{Iterate 'num' in 'numbers'}
    B --> C{Is 'num % 2 == 0'?}
    C -->|Yes| D[Add 'num' to new list]
    C -->|No| B
    D --> B
    B -- End of 'numbers' --> E[End List Comprehension]
    E --> F[Result: even_numbers]

Flowchart of a list comprehension with a filtering 'if' condition

Using 'if/else' for Conditional Transformation

When you need to transform elements differently based on a condition, or provide a default value for elements that don't meet a condition, you use an if/else expression. This structure is placed before the for loop in the comprehension. The syntax is [expression_if_true if condition else expression_if_false for item in iterable].

numbers = [1, 2, 3, 4, 5, 6]
processed_numbers = [num * 2 if num % 2 == 0 else num for num in numbers]
print(processed_numbers)
# Output: [1, 4, 3, 8, 5, 12]

words = ["apple", "banana", "grape", "kiwi"]
capitalized_words = [word.upper() if len(word) > 5 else word for word in words]
print(capitalized_words)
# Output: ['APPLE', 'BANANA', 'grape', 'kiwi']

Transforming elements conditionally using 'if/else'

Combining Filtering and Transformation

It's possible to combine both filtering (if at the end) and conditional transformation (if/else at the beginning) within a single list comprehension. This allows for highly specific list generation, but it's crucial to maintain readability. If the logic becomes too complex, consider breaking it down into multiple steps or using a traditional for loop for clarity.

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Double even numbers, keep odd numbers as is, but only for numbers greater than 3
result = [num * 2 if num % 2 == 0 else num for num in numbers if num > 3]
print(result)
# Output: [5, 8, 7, 12, 9, 16]

Combining 'if/else' for transformation and 'if' for filtering

flowchart TD
    A[Start List Comp] --> B{Iterate 'num' in 'numbers'}
    B --> C{Is 'num > 3'?}
    C -->|No| B
    C -->|Yes| D{Is 'num % 2 == 0'?}
    D -->|Yes| E[Add 'num * 2' to new list]
    D -->|No| F[Add 'num' to new list]
    E --> B
    F --> B
    B -- End of 'numbers' --> G[End List Comp]
    G --> H[Result: result]

Flowchart illustrating combined filtering and conditional transformation