Python List Comprehension: Syntax, Usage, and Examples
Python list comprehension provides a concise way to create lists using a single line of code. It allows you to generate new lists by applying an operation to each item in an existing iterable, often replacing traditional loops for better readability and efficiency.
How to Use List Comprehension in Python
The syntax of a list comprehension follows this structure:
python
[expression for item in iterable]
- expression: Defines the operation to perform on each item.
- item: Represents each element from the iterable.
- iterable: The source data structure (list, tuple, range, etc.).
Example: Creating a List with List Comprehension
python
numbers = [1, 2, 3, 4, 5]
squared_numbers = [n**2 for n in numbers]
print(squared_numbers) # Output: [1, 4, 9, 16, 25]
This example squares each number in the numbers list and stores the results in squared_numbers.
When to Use List Comprehension in Python
List comprehension is useful when you need to:
- Transform data efficiently
- When applying an operation to each element in an iterable (e.g., squaring numbers, converting strings to lowercase).
- Filter elements in a list
- When keeping only specific elements based on a condition (e.g., extracting even numbers).
- Replace loops with a more readable approach
- When improving code readability and reducing the number of lines needed to generate lists.
Examples of List Comprehension in Python
Filtering Elements with a Condition
You can use list comprehension with if statements to filter elements that meet certain conditions.
python
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = [n for n in numbers if n % 2 == 0]
print(even_numbers) # Output: [2, 4, 6]
This example selects only even numbers from the numbers list.
Using if-else in List Comprehension
You can include both if and else to modify values based on a condition.
python
numbers = [1, 2, 3, 4, 5]
squared_or_halved = [n**2 if n % 2 == 0 else n / 2 for n in numbers]
print(squared_or_halved) # Output: [0.5, 4, 1.5, 16, 2.5]
Here, even numbers are squared, and odd numbers are divided by 2.
Using Nested List Comprehension in Python
You can create multidimensional lists with nested list comprehensions.
python
matrix = [[j for j in range(3)] for i in range(3)]
print(matrix)
# Output: [[0, 1, 2], [0, 1, 2], [0, 1, 2]]
This creates a 3x3 matrix where each row contains numbers from 0 to 2.
Using List Comprehension with Dictionaries
List comprehension also works when creating or modifying dictionaries.
python
keys = ['a', 'b', 'c']
values = [1, 2, 3]
dictionary = {k: v for k, v in zip(keys, values)}
print(dictionary) # Output: {'a': 1, 'b': 2, 'c': 3}
This example pairs keys with values using zip().
Learn More About List Comprehension in Python
List Comprehension vs. filter and lambda
List comprehensions often replace filter and lambda for readability.
Using filter and [lambda](/course/glossary.python/lambda-function:
python
numbers = [1, 2, 3, 4, 5]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # Output: [2, 4]
Using list comprehension (more readable):
python
even_numbers = [n for n in numbers if n % 2 == 0]
Double List Comprehension in Python
You can flatten a nested list using double list comprehension.
python
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [num for sublist in nested_list for num in sublist]
print(flattened) # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Using List Comprehension with enumerate
If you need both index and value, use enumerate.
python
words = ["apple", "banana", "cherry"]
indexed_words = [(i, word) for i, word in enumerate(words)]
print(indexed_words) # Output: [(0, 'apple'), (1, 'banana'), (2, 'cherry')]
Using List Comprehension with a Dictionary
You can swap keys and values using dictionary comprehension.
python
original_dict = {'a': 1, 'b': 2, 'c': 3}
swapped = {v: k for k, v in original_dict.items()}
print(swapped) # Output: {1: 'a', 2: 'b', 3: 'c'}
List Comprehension and Generators
If you need an iterable instead of a list, use generator expressions.
python
numbers = (n**2 for n in range(5))
print(list(numbers)) # Output: [0, 1, 4, 9, 16]
Best Practices for List Comprehension
- Use list comprehension for readability, but avoid making expressions too long.
- Prefer list comprehension over loops when creating new lists.
- Use dictionary comprehension when working with key-value pairs.
- Use generator expressions when you don’t need to store the full list in memory.
Python list comprehension simplifies data transformations and makes code more expressive. Whether you need to filter, modify, or generate lists dynamically, list comprehension offers a concise and efficient solution.