Python List Comprehensions with If: Filtering & Tips

目次

1. Introduction

Python’s “list comprehension (List Comprehension)” is a convenient syntax for creating lists concisely. Compared to using a regular for loop to generate a list, it offers advantages in both code readability and execution speed. In particular, combining an if statement with a list comprehension allows you to extract only elements that meet a condition, enabling more flexible list manipulation. This article provides a detailed explanation, from basics to advanced usage, of how to combine Python list comprehensions with if.

What Is a List Comprehension?

A list comprehension is a syntax for creating Python lists concisely. It lets you write shorter, more readable code than using a regular for loop. For example, to create a list of integers from 0 to 4, using a regular for loop looks like this.
numbers = []
for i in range(5):
    numbers.append(i)
print(numbers)  # [0, 1, 2, 3, 4]
However, using a list comprehension, you can write this in a single line.
numbers = [i for i in range(5)]
print(numbers)  # [0, 1, 2, 3, 4]

Benefits of Using List Comprehensions

Using list comprehensions provides the following benefits.
  1. Code becomes shorter and more readable
  • Compared to a regular for loop, you can reduce the number of lines, resulting in cleaner code.
  1. Execution speed improves
  • List comprehensions often run faster than for loops because Python’s internal optimizations apply to them.
  1. List filtering becomes easy
  • By combining an if statement, you can extract only elements that match a specific condition.

Why Use if in a List Comprehension?

Combining if with a list comprehension allows dynamic filtering of list elements. For example, to store only even numbers from 0 to 9 in a list, using a for loop looks like this.
evens = []
for i in range(10):
    if i % 2 == 0:
        evens.append(i)
print(evens)  # [0, 2, 4, 6, 8]
However, with a list comprehension, you can implement this in just one line.
evens = [i for i in range(10) if i % 2 == 0]
print(evens)  # [0, 2, 4, 6, 8]
Thus, by combining if with a list comprehension, you can easily write code that adds only elements meeting a condition to the list.

What You’ll Learn in This Article

In this article, we’ll thoroughly explain the combination of Python list comprehensions and if statements, covering the following topics.
  • Basic syntax of list comprehensions
  • Conditional list comprehensions using if
  • List comprehensions with if-else
  • Using nested list comprehensions
  • Cautions and best practices when using list comprehensions
  • Frequently Asked Questions (FAQ)
By leveraging list comprehensions, you can write Python code that is simpler and more efficient. We’ll go into detail from here, so please read to the end and deepen your understanding by writing code yourself!

2. Basics of Python List Comprehensions

In the previous section, we introduced what list comprehensions are and their benefits. From here, we will explain the basic syntax of list comprehensions in detail and deepen understanding through concrete examples.

Basic Syntax of List Comprehensions

The basic syntax of a list comprehension looks like this.
[expression for variable in iterable]

Elements of the Syntax

  • expression: The operation applied to the variable (calculations, functions, etc.)
  • for variable in iterable: Loop that extracts each element from an iterable (list, tuple, range, etc.)
For example, to create a list containing integers from 0 to 4, using a regular for loop looks like this.
numbers = []
for i in range(5):
    numbers.append(i)
print(numbers)  # [0, 1, 2, 3, 4]
However, using a list comprehension, you can write this in a single line.
numbers = [i for i in range(5)]
print(numbers)  # [0, 1, 2, 3, 4]

Basic Examples of List Comprehensions

List comprehensions make creating and transforming lists easy. Here are several basic examples.

1. Squaring Each Element

An example that stores the squares of numbers from 0 to 9 in a list using a list comprehension.
squares = [i**2 for i in range(10)]
print(squares)  # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Compared to writing it with a regular for loop, you can see that the code is dramatically shortened.
squares = []
for i in range(10):
    squares.append(i**2)
print(squares)  # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

2. Transforming a List of Strings

An example that converts all strings in a list to uppercase.
words = ["python", "list", "comprehension"]
uppercase_words = [word.upper() for word in words]
print(uppercase_words)  # ['PYTHON', 'LIST', 'COMPREHENSION']
Writing the same process with a for loop looks like this.
words = ["python", "list", "comprehension"]
uppercase_words = []
for word in words:
    uppercase_words.append(word.upper())
print(uppercase_words)  # ['PYTHON', 'LIST', 'COMPREHENSION']
Using a list comprehension allows you to write data transformation code simply.

3. Flattening a List (Extracting Elements from a Nested List)

List comprehensions are also handy for converting a nested list (2‑dimensional list) into a one‑dimensional list.
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [num for row in matrix for num in row]
print(flattened)  # [1, 2, 3, 4, 5, 6, 7, 8, 9]
When written with a regular for loop, a nested loop is required as follows.
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = []
for row in matrix:
    for num in row:
        flattened.append(num)
print(flattened)  # [1, 2, 3, 4, 5, 6, 7, 8, 9]
Using a list comprehension shows that you can write nested loops more simply.

Comparison of List Comprehensions and Regular for Loops

ItemList ComprehensionRegular for Loop
Code LengthShort (can be written in one line)Long (requires multiple lines)
ReadabilitySimple and intuitive (easy to understand for simple tasks)More readable when longer, but can become verbose
Execution SpeedFast (benefits from Python’s internal optimizations)Slightly slower (due to explicit loop processing)
Readability LimitsBecomes hard to read when nesting gets deepEasier to organize even with deep nesting
In general, use list comprehensions for simple tasks and regular for loops for complex tasks.

Summary

  • List comprehensions are a convenient feature that lets you create lists with concise syntax
  • The basic syntax is [expression for variable in iterable]
  • Can be used for numeric calculations, string transformations, list flattening, and many other purposes
  • Results in shorter code and faster execution compared to regular for loops
  • However, be aware that readability decreases as nesting deepens

3. if Conditional List Comprehension Using if

In the previous section, we learned the basics of list comprehensions. From here, we will explain how to combine if with list comprehensions to create conditional lists. Adding if list comprehension makes filtering easier, allowing you to add only elements that meet specific conditions to the list.

Basic Syntax of List Comprehensions Using if

When creating a list with a condition, the basic syntax is as follows.
[expression for variable in iterable if condition]

Elements of the Syntax

  • expression: The operation applied to each element
  • for variable in iterable: Loop over an iterable (list, tuple, range, etc.)
  • if condition: Add to the list only when the condition is satisfied using an if statement

Basic Examples

1. Extract Even Numbers Only

For example, to store only the even integers from 0 to 9 in a list, using a regular for loop looks like this.
evens = []
for i in range(10):
    if i % 2 == 0:
        evens.append(i)
print(evens)  # [0, 2, 4, 6, 8]
Using a list comprehension, you can write it concisely as follows.
evens = [i for i in range(10) if i % 2 == 0]
print(evens)  # [0, 2, 4, 6, 8]
→ By incorporating the if statement into the list comprehension, you can omit the extra append(), making the code shorter.

2. Filtering a List of Strings

Using a list comprehension, you can also extract only the elements that meet specific conditions from a list of strings. For example, to store only programming languages with five or more characters from “python”, “java”, “c++”, “ruby”, you would write:
languages = ["python", "java", "c++", "ruby"]
long_languages = [lang for lang in languages if len(lang) >= 5]
print(long_languages)  # ['python']

3. Extract Words Containing a Specific Character

You can also use a list comprehension to extract only the words that contain a specific character. For example, to extract only words that contain "a", you can write:
words = ["apple", "banana", "cherry", "date"]
words_with_a = [word for word in words if "a" in word]
print(words_with_a)  # ['apple', 'banana', 'date']

How to Specify Multiple Conditions

When specifying multiple conditions in an if statement, you can use and or or.

1. Extract Numbers That Are Both Even and Multiples of 3

filtered_numbers = [i for i in range(20) if i % 2 == 0 and i % 3 == 0]
print(filtered_numbers)  # [0, 6, 12, 18]

2. Extract Strings That Satisfy Multiple Conditions

words = ["python", "java", "c++", "ruby", "go", "haskell"]
filtered_words = [word for word in words if len(word) >= 5 and "o" in word]
print(filtered_words)  # ['python']

Common Errors and Solutions

1. Misplacing the if

Incorrect Example (Improper placement of if)
numbers = [if i % 2 == 0 for i in range(10)]
Error: SyntaxError: invalid syntaxCorrect Example
numbers = [i for i in range(10) if i % 2 == 0]

2. Misusing and / or

Incorrect Example
words = ["apple", "banana", "cherry"]
filtered_words = [word for word in words if len(word) > 5 or "a" in word]
Use and to achieve the expected result
filtered_words = [word for word in words if len(word) > 5 and "a" in word]

Summary

  • Adding if to a list comprehension allows you to store only elements that meet the condition in the list
  • The syntax is [expression for variable in iterable if condition]
  • It can be used for various purposes such as extracting even numbers, filtering strings, etc.
  • When specifying multiple conditions, leverage and / or
  • Be careful: placing if incorrectly or writing conditions wrong will cause errors

4. List comprehension using if-else

In the previous section, we learned how to filter list elements using if. However, if you want to store different values in the list depending on the condition, you need to combine if-else. In this section, we will explain in detail how to write list comprehensions using if-else and provide practical examples.

if-else List comprehension basic syntax

The syntax for incorporating if-else into a list comprehension is as follows.
[expr1 if condition else expr2 for var in iterable]

Syntax elements

  • expr1: the value or operation applied when condition is satisfied
  • condition: the condition specified by if
  • else expr2: the value or operation applied when condition is not satisfied
  • for var in iterable: loop over an iterable (list, range, etc.)
When using if-else, note that if comes before for! → When using only if, it is written after for, but when using if-else, it must be written before for.

Basic usage examples

1. Keep even numbers as is, convert odd numbers to “odd”

For example, to store even numbers as they are in a list and convert odd numbers to “odd” for integers from 0 to 9, a regular for loop looks like this.
numbers = []
for i in range(10):
    if i % 2 == 0:
        numbers.append(i)
    else:
        numbers.append("odd")

print(numbers)  
# [0, 'odd', 2, 'odd', 4, 'odd', 6, 'odd', 8, 'odd']
Using a list comprehension, you can write this in one line.
numbers = [i if i % 2 == 0 else "odd" for i in range(10)]
print(numbers)  
# [0, 'odd', 2, 'odd', 4, 'odd', 6, 'odd', 8, 'odd']
→ Using if and else shows that you can flexibly transform list values.

2. Convert values ≤ 0 to “negative”

For example, consider processing where numbers in a list that are less than or equal to 0 are converted to "negative", while other numbers are kept as is.
numbers = [-5, 3, 0, 8, -2, 7]
modified_numbers = [num if num > 0 else "negative" for num in numbers]
print(modified_numbers)  
# ['negative', 3, 'negative', 8, 'negative', 7]

3. Classify numbers as positive or negative

For example, to classify integers in a list as “positive” (positive numbers) and “negative” (negative numbers), you can write as follows.
numbers = [-10, 15, 0, -5, 20]
categories = ["positive" if num > 0 else "negative" for num in numbers]
print(categories)  
# ['negative', 'positive', 'negative', 'negative', 'positive']

Precautions when using if-else in list comprehensions

1. Do not place if incorrectly

Incorrect example (causes error)
numbers = [i for i in range(10) if i % 2 == 0 else "odd"]
Error: SyntaxError: invalid syntaxCorrect syntax
numbers = [i if i % 2 == 0 else "odd" for i in range(10)]
👉 When using if-else, it must be placed before for!

2. Difference between if-else and if

  • When using only if (element filtering)
  evens = [i for i in range(10) if i % 2 == 0]
  print(evens)  # [0, 2, 4, 6, 8]
→ When using only if, elements that do not satisfy the condition are not included in the list.
  • When using if-else (value transformation)
  numbers = [i if i % 2 == 0 else "odd" for i in range(10)]
  print(numbers)  # [0, 'odd', 2, 'odd', 4, 'odd', 6, 'odd', 8, 'odd']
→ Using if-else includes all elements in the list, converting them according to the condition.

Summary

  • Using if-else lets you store different values in a list based on conditions
  • When using if-else, write it before for
  • Unlike list comprehensions with only if, you can include all elements while converting them
  • Useful for classifying numbers or strings and changing values under specific conditions
  • Using nested if-else allows combining multiple conditions
侍エンジニア塾

5. Nested List Comprehensions and Conditional Branching

In the previous section, we learned about list comprehensions using if-else. In this section, we will explain how to use nested list comprehensions (list comprehensions that include multiple loops). In list comprehensions, you can use multiple loops (nesting) just like a regular for loop. This allows you to process lists of lists (such as two‑dimensional lists) effectively.

Basic Syntax of Nested List Comprehensions

The basic syntax for nesting loops in a list comprehension is as follows.
[expression for var1 in iterable1 for var2 in iterable2]

Elements of the Syntax

  • expression: The operation applied to each element
  • for var1 in iterable1: The first loop
  • for var2 in iterable2: The inner loop (nested loop)
The key point is that, just like a regular for loop, the loops execute from left to right.

Basic Examples

1. Flattening a 2‑Dimensional List

For example, to convert a two‑dimensional list (a list of lists) into a one‑dimensional list, a regular for loop would look like this.
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = []
for row in matrix:
    for num in row:
        flattened.append(num)
print(flattened)  
# [1, 2, 3, 4, 5, 6, 7, 8, 9]
Using a list comprehension, you can write it in a single line like this.
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [num for row in matrix for num in row]
print(flattened)  
# [1, 2, 3, 4, 5, 6, 7, 8, 9]
→ Applying loop nesting to a list comprehension lets you write shorter, more intuitive code.

2. Creating All Combinations

For example, to create all combinations of A, B, C and 1, 2, 3, a regular for loop would look like this.
letters = ["A", "B", "C"]
numbers = [1, 2, 3]
combinations = []

for letter in letters:
    for number in numbers:
        combinations.append(f"{letter}{number}")

print(combinations)  
# ['A1', 'A2', 'A3', 'B1', 'B2', 'B3', 'C1', 'C2', 'C3']
Using a list comprehension, you can write it concisely like this.
letters = ["A", "B", "C"]
numbers = [1, 2, 3]
combinations = [f"{letter}{number}" for letter in letters for number in numbers]

print(combinations)  
# ['A1', 'A2', 'A3', 'B1', 'B2', 'B3', 'C1', 'C2', 'C3']
The strength of nested list comprehensions is that you can write multiple loops in a single line.

Combining Conditional Branching

Even with nested list comprehensions, you can incorporate conditional branching using if or if-else.

3. Getting Only Even Pairs

For example, if you want to obtain only the pairs from the combinations of 1–3 and 4–6 whose sum is even, a regular for loop would look like this.
list1 = [1, 2, 3]
list2 = [4, 5, 6]
pairs = []

for x in list1:
    for y in list2:
        if (x + y) % 2 == 0:
            pairs.append((x, y))

print(pairs)  
# [(1, 5), (2, 4), (2, 6), (3, 5)]
Using a list comprehension makes it shorter and more intuitive.
list1 = [1, 2, 3]
list2 = [4, 5, 6]
pairs = [(x, y) for x in list1 for y in list2 if (x + y) % 2 == 0]

print(pairs)  
# [(1, 5), (2, 4), (2, 6), (3, 5)]

Cautions When Using Nested List Comprehensions

1. Readability can easily degrade
  • Avoid excessive use because readability decreases as nesting gets deeper
  • If readability is a priority, use a regular for loop
2. Pay attention to the position of if
  • When using only if, place it after the for
  • When using if-else, place it before the for
3. Factor out into functions if nesting becomes too complex
  • If nesting becomes deep and readability suffers, one approach is to avoid list comprehensions and split the logic into functions.

Summary

  • Using nested list comprehensions lets you handle 2‑dimensional lists and multiple loops concisely
  • if can be combined to extract only elements that meet the condition
  • Combining if-else allows you to assign different values for each element
  • However, be careful as excessive nesting can reduce readability

6. Best Practices and Pitfalls of List Comprehensions

List comprehensions are a handy feature that let you write Python code more concisely, but depending on how you use them, they can reduce readability or degrade performance。 In this section, we will explain best practices and pitfalls for using list comprehensions effectively

When to Use List Comprehensions

List comprehensions are suitable in the following cases.

1. Simple List Creation

Because list comprehensions make it easy to create lists, they are especially well-suited for simple element transformation or extraction tasksExample: Squaring each element
squares = [x**2 for x in range(10)]
print(squares)  # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

2. Conditional List Creation (Filtering)

When you need to extract only elements that meet specific conditions, list comprehensions are also appropriate。 Example: Extracting even numbers
evens = [x for x in range(10) if x % 2 == 0]
print(evens)  # [0, 2, 4, 6, 8]

3. Transforming Lists of Strings

List comprehensions are also handy when transforming a list of stringsExample: Converting all strings to uppercase
words = ["python", "list", "comprehension"]
uppercase_words = [word.upper() for word in words]
print(uppercase_words)  # ['PYTHON', 'LIST', 'COMPREHENSION']

4. Flattening Nested Lists

When converting a 2D list to a 1D list, it is also useful。 Example: Flattening a 2D list
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [num for row in matrix for num in row]
print(flattened)  # [1, 2, 3, 4, 5, 6, 7, 8, 9]

When Not to Use List Comprehensions

List comprehensions are convenient, but there are cases where they are not appropriate。

1. Deep Nesting Reduces Readability

List comprehensions are readable for simple tasks, but when loops become nested, readability suffers❌ Bad example: List comprehension with multiple nested loops
matrix = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
flattened = [num for row in matrix for subrow in row for num in subrow]
👉 Too deeply nested to be understandable ✅ Solution: Use regular for loops
flattened = []
for row in matrix:
    for subrow in row:
        for num in subrow:
            flattened.append(num)

2. Writing Overly Long Logic in a Comprehension Reduces Readability

List comprehensions have the advantage of being simple and concise in a single line, but adding complex logic makes them harder to read❌ Bad example: List comprehension packed with complex conditions
numbers = [x**2 if x % 2 == 0 else x**3 for x in range(10) if x != 5 and x % 3 != 0]
👉 The conditions become overly complex and hard to read ✅ Solution: Use a for loop
numbers = []
for x in range(10):
    if x != 5 and x % 3 != 0:
        if x % 2 == 0:
            numbers.append(x**2)
        else:
            numbers.append(x**3)

Performance of List Comprehensions

1. Faster Execution Compared to for Loops

List comprehensions are generally faster than for loops. Python’s internal optimizations make list creation more efficient。 for Loop vs List Comprehension Speed Comparison
import time

# Comparison with large data
data = list(range(10**6))

# List comprehension
start = time.time()
squares = [x**2 for x in data]
print("List comprehension:", time.time() - start)

# Regular for loop
start = time.time()
squares = []
for x in data:
    squares.append(x**2)
print("Regular for loop:", time.time() - start)
Result
  • List comprehensions tend to be faster
  • However, because the entire list is stored in memory, memory usage increases with large data

2. Use Generator Expressions for Memory Efficiency

When handling large data, using a generator expression instead of a list comprehension can reduce memory usage
# List comprehension (high memory consumption)
squares = [x**2 for x in range(10**6)]

# Generator expression (memory efficient)
squares_gen = (x**2 for x in range(10**6))
squares_gen does not create a list and returns an iterator, saving memory.

Summary

When to Use List Comprehensions
  • Simple list creation
  • Filtering
  • String transformation
  • Flattening 2D lists
When to Avoid List Comprehensions
  • Deeply nested processing
  • Overly complex conditions
  • When readability becomes extremely poor
💡 Best Practices
  • Use list comprehensions for simple tasks
  • Use regular for loops for complex tasks
  • Choose appropriately based on performance considerations

7. Frequently Asked Questions (FAQ)

In this section, we provide a detailed explanation of common questions about list comprehensions and the points to watch out for when developing. It also covers pitfalls that beginners often encounter and performance-related concerns.

Q1. Is it possible to use if twice for conditional filtering?

A1. Yes, it’s possible, but you need to be careful about readability.

In list comprehensions, you can use if more than once to specify complex conditions. Example: Extract only numbers that satisfy two conditions (even and a multiple of 3)
filtered_numbers = [x for x in range(30) if x % 2 == 0 if x % 3 == 0]
print(filtered_numbers)  # [0, 6, 12, 18, 24]
Thus, writing if consecutively works like an “AND condition”. However, for readability, it’s clearer to use and.
filtered_numbers = [x for x in range(30) if x % 2 == 0 and x % 3 == 0]

Q2. Should you use list comprehensions or regular for loops?

A2. Choose based on simplicity of the operation and readability.

List comprehensions are very useful for simple operations, but they can reduce readability for complex operations. Example: Cases where a regular for loop is preferable
# ❌ List comprehension is hard to read
numbers = ["Even" if x % 2 == 0 else "Odd" if x % 3 == 0 else "Other" for x in range(10)]

# ✅ Regular `for` loop is clearer
numbers = []
for x in range(10):
    if x % 2 == 0:
        numbers.append("Even")
    elif x % 3 == 0:
        numbers.append("Odd")
    else:
        numbers.append("Other")

Q3. What’s the difference between using if-else and using only if?

A3. if alone is for filtering, while if-else is for value transformation.

if only (retrieve elements that meet the condition)
evens = [x for x in range(10) if x % 2 == 0]
print(evens)  # [0, 2, 4, 6, 8]
→ Only even numbers are extracted, and elements that don’t meet the condition are not included in the list if-else (store different values based on the condition
RUNTEQ(ランテック)|超実戦型エンジニア育成スクール