Python has a feature called “List Comprehensions” that allows you to concisely create a new list based on an existing list (or other iterables). This is one of Python’s key features. Compared to using a standard for loop with append(), the code becomes shorter and often runs faster.
This article explains the basic syntax of list comprehensions and how to filter elements using conditions (if).
1. Basic Syntax of List Comprehensions
List comprehensions are written by embedding a for loop inside square brackets [].
Syntax:
[expression for variable in iterable]
Specific Example
Let’s look at an example where we create a “tax-included price list” (adding 10% tax) from a “base price list”.
# List of base prices
base_prices = [100, 250, 500, 980]
# Using List Comprehension
# Multiply each element (price) by 1.1 to create a new list
tax_included = [int(price * 1.1) for price in base_prices]
print(f"Base: {base_prices}")
print(f"Tax Included: {tax_included}")
Output:
Base: [100, 250, 500, 980]
Tax Included: [110, 275, 550, 1078]
2. Comparison with Standard for Loop
If you were to write the same logic without list comprehensions, using a standard for loop and the .append() method, it would look like this:
base_prices = [100, 250, 500, 980]
tax_included_loop = []
# Using a standard for loop
for price in base_prices:
tax_included_loop.append(int(price * 1.1))
print(f"Result with loop: {tax_included_loop}")
Output:
Result with loop: [110, 275, 550, 1078]
The result is the same, but list comprehensions are superior because:
- You don’t need to create an empty list (
tax_included_loop = []) beforehand. - You don’t need to write
append. - The process is completed in a single line.
3. Conditional List Comprehensions (Filtering with if)
By adding an if statement at the end of the list comprehension, you can extract and process only the elements that meet a specific condition.
Syntax:
[expression for variable in iterable if condition]
Specific Example
Here is an example of extracting only passing scores (70 points or higher) from a list of test scores.
# List of test scores
all_scores = [65, 90, 45, 80, 72, 55]
# Extract only scores of 70 or higher
passing_scores = [score for score in all_scores if score >= 70]
print(f"All Scores: {all_scores}")
print(f"Passing Scores: {passing_scores}")
Output:
All Scores: [65, 90, 45, 80, 72, 55]
Passing Scores: [90, 80, 72]
This code performs the same action as the following standard for loop:
passing_scores_loop = []
for score in all_scores:
if score >= 70:
passing_scores_loop.append(score)
By using list comprehension, we reduced 4 lines of code to just 1 line.
Summary
- List comprehensions are a concise syntax for creating new lists.
- Write them in the format:
[expression for variable in list]. - You can filter specific elements by adding
ifat the end. - For simple list creation or transformation tasks, this method is more readable and is considered “Pythonic.”
