Python List Comprehension
List comprehension is one of Python's most elegant and powerful features that allows you to create lists in a concise and readable way. It combines the functionality of a for
loop, conditional statements, and list creation into a single line of code. In this tutorial, you'll learn how to use list comprehensions effectively in your Python programs.
Introduction to List Comprehension
In traditional programming, creating a list often requires initializing an empty list and then appending elements using a for
loop. List comprehension provides a more Pythonic approach to achieve the same result.
Let's compare the traditional approach with list comprehension:
Traditional Approach:
# Creating a list of squares from 0 to 9
squares = []
for i in range(10):
squares.append(i ** 2)
print(squares)
Output:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Using List Comprehension:
# Creating the same list using list comprehension
squares = [i ** 2 for i in range(10)]
print(squares)
Output:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
As you can see, list comprehension accomplishes the same task in a more concise and readable way.
Basic Syntax of List Comprehension
The basic syntax for list comprehension is:
[expression for item in iterable]
Where:
expression
: The operation to perform on each itemitem
: The variable representing each element in the iterableiterable
: A sequence, collection, or any object that can be iterated over
List Comprehension with Conditional Statements
You can add conditional statements to filter elements from the original iterable. This makes list comprehension even more powerful.
Using a Single Condition (if)
# Get only even numbers from 0 to 9
even_numbers = [i for i in range(10) if i % 2 == 0]
print(even_numbers)
Output:
[0, 2, 4, 6, 8]
Using if-else in List Comprehension
You can also use an if-else
conditional expression within the list comprehension:
# Mark numbers as 'even' or 'odd'
number_types = ['even' if i % 2 == 0 else 'odd' for i in range(5)]
print(number_types)
Output:
['even', 'odd', 'even', 'odd', 'even']
Note the difference in syntax when using if-else
versus a simple if
. When using if-else
, the conditional comes before the for
clause.
Nested List Comprehension
List comprehensions can be nested to create more complex structures like matrices:
# Create a 3x3 matrix
matrix = [[i * j for j in range(1, 4)] for i in range(1, 4)]
print(matrix)
Output:
[[1, 2, 3], [2, 4, 6], [3, 6, 9]]
Let's break down what happened:
- The outer comprehension creates the rows:
for i in range(1, 4)
- The inner comprehension creates the columns:
for j in range(1, 4)
- Each value is calculated as:
i * j
Practical Examples
Let's explore some real-world applications of list comprehension:
Example 1: Filtering a List of Strings
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
fruits_with_a = [fruit for fruit in fruits if "a" in fruit]
print(fruits_with_a)
Output:
['apple', 'banana', 'mango']
Example 2: Converting Temperature from Celsius to Fahrenheit
celsius = [0, 10, 20, 30, 40]
fahrenheit = [(9/5) * temp + 32 for temp in celsius]
print(fahrenheit)
Output:
[32.0, 50.0, 68.0, 86.0, 104.0]
Example 3: Extracting Data from a Dictionary
student_scores = {"John": 85, "Mary": 90, "David": 75, "Emma": 95}
high_performers = [name for name, score in student_scores.items() if score >= 90]
print(high_performers)
Output:
['Mary', 'Emma']
Example 4: Flattening a 2D List
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [item for row in matrix for item in row]
print(flattened)
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Performance Considerations
List comprehensions are not only more concise but often faster than traditional for
loops for creating lists. This is because list comprehensions are optimized at the C level in CPython.
However, it's important to consider readability. For very complex operations, a regular for
loop might be more readable and maintainable.
import time
# Timing a for loop vs. list comprehension
start = time.time()
squares_loop = []
for i in range(1000000):
squares_loop.append(i ** 2)
loop_time = time.time() - start
start = time.time()
squares_comp = [i ** 2 for i in range(1000000)]
comp_time = time.time() - start
print(f"For loop time: {loop_time:.5f} seconds")
print(f"List comprehension time: {comp_time:.5f} seconds")
Output (results may vary):
For loop time: 0.15427 seconds
List comprehension time: 0.07312 seconds
When to Use List Comprehension
List comprehensions are most suitable when:
- You need to create a new list based on an existing list or iterable
- The transformation logic is simple and can be expressed concisely
- You want to filter elements based on a condition
It's better to use regular loops when:
- The logic is complex and would make the comprehension hard to read
- There are multiple operations that need to happen for each item
- You're not actually collecting results in a list (use a generator expression instead)
Summary
List comprehension is a powerful and elegant Python feature that allows you to create lists in a concise and readable way. It combines the functionality of loops, conditional statements, and list creation into a single line of code.
Key points to remember:
- Basic syntax:
[expression for item in iterable]
- Filtering:
[expression for item in iterable if condition]
- Conditional expression:
[true_exp if condition else false_exp for item in iterable]
- List comprehensions are often more efficient than equivalent for loops
- Prioritize readability over conciseness for complex operations
Exercises
- Create a list of the first 10 square numbers (1, 4, 9, ..., 100)
- Create a list containing only the vowels from a given string
- Convert a list of strings to uppercase using list comprehension
- Create a list of tuples containing (number, square, cube) for numbers 1 to 5
- Filter out negative numbers from a list using list comprehension
Additional Resources
- Python Documentation on List Comprehensions
- PEP 202 – List Comprehensions
- Real Python: When to Use a List Comprehension in Python
Happy coding with Python list comprehensions!
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)