List comprehension is a concise way to create a new list from an existing iterable such as a list, tuple, string, or range. It allows you to combine list creation, iteration, and simple conditions into a single expression.
List comprehension is especially useful when the operation is simple and repetitive. Instead of writing several lines with a for loop and append(), the same logic can often be expressed in one readable line.
Table of Contents
What Is List Comprehension?
List comprehension is a Python feature used to create a new list by applying an expression to each item of an iterable. It can also include a condition when only specific items need to be included.
The basic form of a list comprehension is:
[expression for item in iterable]
Here, expression defines what will be stored in the new list, item represents the current value being processed, and iterable is the source of the values.
For example, we can create a list containing the squares of numbers from another list.
numbers = [1, 2, 3, 4, 5]
squares = [number ** 2 for number in numbers]
print(squares)
Output:
[1, 4, 9, 16, 25]
Python takes each value from numbers, calculates its square, and places the result into the new list.
Why Use List Comprehension?
List comprehension is useful when you need to create a list by applying the same operation to multiple values. It can make simple list-building operations shorter without changing their basic logic.
It is commonly used for transforming values, filtering data, and creating sequences from ranges or other iterables.
- Creates a new list in a compact form.
- Replaces simple for loops used for building lists.
- Transforms every item in an iterable.
- Filter items using a condition.
- Combines iteration and conditional logic.
List Comprehension vs Traditional for Loop
A list comprehension and a traditional for loop can often perform the same task. The main difference is that the traditional loop usually creates an empty list first and then adds values using append(), while list comprehension creates the resulting list directly.
Using a Traditional for Loop
numbers = [1, 2, 3, 4, 5]
squares = []
for number in numbers:
squares.append(number ** 2)print(squares)
Output:
[1, 4, 9, 16, 25]
The loop processes each number and adds its square to squares.
Using List Comprehension
numbers = [1, 2, 3, 4, 5]
squares = [number ** 2 for number in numbers]
print(squares)
Output:
[1, 4, 9, 16, 25]
Both approaches produce the same result. List comprehension simply expresses the list-building operation more compactly.
| Traditional for Loop | List Comprehension |
|---|---|
| Usually requires an empty list. | Creates the new list directly. |
| Usually requires append(). | No append() is required. |
| Uses multiple lines for simple operations. | Can express simple operations in one line. |
| Can be easier for complex logic. | Best suited for simple and readable logic. |
Basic Syntax of List Comprehension
A list comprehension has three main parts: the expression, the for clause, and the iterable. These parts work together to determine what values are generated and where they come from.
The basic syntax is:
[expression for item in iterable]
For example:
numbers = [10, 20, 30, 40]
result = [number + 5 for number in numbers]
print(result)
Output:
[15, 25, 35, 45]
Each number is increased by 5, and the resulting values are stored in result.
1. Expression
The expression determines the value that will be placed into the resulting list. It can be the original item, a calculation, a method call, or another simple expression.
[number * 2 for number in numbers]
Here, number * 2 is the expression.
2. Item
The item is the variable that represents the current value during each iteration. Its name can be chosen according to the data being processed.
[number * 2 for number in numbers]
Here, number represents each value from numbers one at a time.
3. Iterable
The iterable is the source from which the values are taken. It can be a list, tuple, string, range, or another iterable object.
[number * 2 for number in numbers]
Here, numbers is the iterable.
Simple List Comprehension
The simplest list comprehension applies an expression to every item in an iterable. Since there is no condition, every item is processed and included in the resulting list.
For example, we can multiply every number by 2.
numbers = [1, 2, 3, 4, 5]
result = [number * 2 for number in numbers]
print(result)
Output:
[2, 4, 6, 8, 10]
The expression number * 2 is evaluated for every value in numbers.
List Comprehension with Expressions
The expression in a list comprehension can perform calculations or other simple operations on each item. This makes list comprehension useful for transforming existing data.
1. Squaring Numbers
numbers = [1, 2, 3, 4]
squares = [number ** 2 for number in numbers]
print(squares)
Output:
[1, 4, 9, 16]
Each number is raised to the power of 2 before being stored in the new list.
2. Adding a Value
numbers = [10, 20, 30]
result = [number + 10 for number in numbers]
print(result)
Output:
[20, 30, 40]
The expression adds 10 to every value.
3. Converting Values
A list comprehension can also apply a conversion to every item. For example, integers can be converted into strings.
numbers = [1, 2, 3, 4]
result = [str(number) for number in numbers]
print(result)
Output:
['1', '2', '3', '4']
Each integer is converted to a string before being added to the new list.
List Comprehension with a Condition
A condition can be added when you want to include only certain items in the resulting list. The filtering condition is placed after the for clause.
The syntax is:
[expression for item in iterable if condition]
For example, we can select only even numbers.
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = [number for number in numbers if number % 2 == 0]
print(even_numbers)
Output:
[2, 4, 6]
Python checks the condition for each number. Only numbers that satisfy the condition are added to the new list.
1. Filtering Odd Numbers
The same pattern can be used to select odd numbers. Only the condition needs to be changed.
numbers = [1, 2, 3, 4, 5, 6]
odd_numbers = [number for number in numbers if number % 2 != 0]
print(odd_numbers)
Output:
[1, 3, 5]
Only numbers that are not divisible by 2 are included.
2. Filtering Values Greater Than a Number
A condition does not have to check whether a number is even or odd. It can use any suitable comparison.
numbers = [5, 12, 8, 20, 3]
result = [number for number in numbers if number > 10]
print(result)
Output:
[12, 20]
Only values greater than 10 satisfy the condition.
List Comprehension with if-else
An if-else expression is useful when every item should produce a value, but the value depends on a condition. In this form, the if-else expression appears before the for clause.
The syntax is:
[value_if_true if condition else value_if_false for item in iterable]
For example, we can label each number as even or odd.
numbers = [1, 2, 3, 4, 5]
result = ["Even" if number % 2 == 0 else "Odd" for number in numbers]
print(result)
Output:
['Odd', 'Even', 'Odd', 'Even', 'Odd']
Every number produces a result. If the condition is true, "Even" is selected; otherwise, "Odd" is selected.
Filtering vs if-else
Filtering and if-else serve different purposes. Filtering removes items that do not satisfy a condition, while if-else produces one value for every item.
| Purpose | Pattern |
|---|---|
| Filter items | [expression for item in iterable if condition] |
| Choose a value | [value1 if condition else value2 for item in iterable] |
List Comprehension with range()
range() can be used as the iterable in a list comprehension. This is useful when you want to generate a sequence of numbers and optionally transform or filter them.
1. Creating a Sequence
numbers = [number for number in range(1, 6)]
print(numbers)
Output:
[1, 2, 3, 4, 5]
range(1, 6) produces values from 1 up to, but not including, 6.
2. Creating Squares
squares = [number ** 2 for number in range(1, 6)]
print(squares)
Output:
[1, 4, 9, 16, 25]
Each number generated by range() is squared before being placed into the list.
3. Creating Even Numbers
even_numbers = [number for number in range(1, 11) if number % 2 == 0]
print(even_numbers)
Output:
[2, 4, 6, 8, 10]
The condition filters the sequence so that only even numbers are included.
List Comprehension with Strings
Strings are iterable, which means list comprehension can process their characters one by one. This makes it possible to create lists of characters or transform selected characters.
1. Creating a List of Characters
word = "python"
letters = [letter for letter in word]
print(letters)
Output:
['p', 'y', 't', 'h', 'o', 'n']
Each character of the string becomes an item in the new list.
2. Converting Characters to Uppercase
word = "python"
letters = [letter.upper() for letter in word]
print(letters)
Output:
['P', 'Y', 'T', 'H', 'O', 'N']
The upper() method is applied to every character.
3. Extracting Vowels
A filtering condition can be used to select only particular characters from a string. For example, we can extract the vowels from a word.
word = "python"
vowels = [letter for letter in word if letter in "aeiou"]
print(vowels)
Output:
['o']
Only characters that are present in "aeiou" are included.
List Comprehension with Other Iterables
List comprehension is not limited to lists. Any iterable can be used as the source, including tuples, strings, ranges, and other iterable objects.
1. Using a Tuple
numbers = (1, 2, 3, 4)
squares = [number ** 2 for number in numbers]
print(squares)
Output:
[1, 4, 9, 16]
The values are taken from the tuple and used to create a new list.
2. Using a Set
A set can also be used as the iterable. However, because sets are unordered collections, the order of the resulting list should not be relied upon.
numbers = {1, 2, 3, 4}
squares = [number ** 2 for number in numbers]
print(sorted(squares))
Output:
[1, 4, 9, 16]
The list comprehension processes the values from the set, while sorted() is used here to display the resulting values in a predictable order.
Nested List Comprehension
A list comprehension can contain more than one for clause. This is useful when working with nested lists or when you need to generate combinations of values.
For example:
pairs = [(x, y) for x in range(1, 3) for y in range(1, 4)]
print(pairs)
Output:
[(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3)]
The second for clause runs for every value produced by the first for clause.
Flattening a Nested List
Nested list comprehension can be used to convert a nested list into a single list. The outer for processes each inner list, while the inner for processes each value inside it.
numbers = [[1, 2], [3, 4], [5, 6]]
result = [number for row in numbers for number in row]
print(result)
Output:
[1, 2, 3, 4, 5, 6]
The values from all three inner lists are collected into one new list.
Practical Examples
List comprehension is commonly used for simple data-processing operations. The following examples show how the same pattern can be applied to numerical and text-based data.
1. Creating a List of Positive Numbers
numbers = [-5, 3, -2, 8, -1, 6]
positive_numbers = [number for number in numbers if number > 0]
print(positive_numbers)
Output:
[3, 8, 6]
The condition keeps only numbers greater than zero.
2. Converting Names to Uppercase
names = ["alice", "bob", "charlie"]
uppercase_names = [name.upper() for name in names]
print(uppercase_names)
Output:
['ALICE', 'BOB', 'CHARLIE']
The upper() method is applied to every name.
3. Finding Long Words
words = ["cat", "python", "book", "programming"]
long_words = [word for word in words if len(word) > 4]
print(long_words)
Output:
['python', 'programming']
Only words containing more than four characters are included.
4. Converting Celsius to Fahrenheit
celsius = [0, 10, 20, 30]
fahrenheit = [(temperature * 9 / 5) + 32 for temperature in celsius]
print(fahrenheit)
Output:
[32.0, 50.0, 68.0, 86.0]
The expression applies the Fahrenheit conversion formula to every Celsius value.
List Comprehension with Multiple Conditions
More than one condition can be used when the filtering logic requires it. Each condition must be satisfied for an item to be included.
For example, we can select numbers that are both even and greater than 5.
numbers = [2, 4, 6, 8, 10, 12]
result = [number for number in numbers if number % 2 == 0 and number > 5]
print(result)
Output:
[6, 8, 10, 12]
The number must satisfy both conditions to be included.
Edge Cases in List Comprehension
List comprehensions generally behave predictably, but some situations are worth understanding. Empty iterables, conditions with no matches, and nested data can all affect the resulting list.
1. Empty Iterable
If the iterable is empty, there are no items to process, so the result is an empty list.
numbers = []
result = [number * 2 for number in numbers]
print(result)
Output:
[]
2.No Matching Items
If no item satisfies a filtering condition, the resulting list is also empty. This is normal behavior and does not produce an error.
numbers = [1, 3, 5]
result = [number for number in numbers if number % 2 == 0]
print(result)
Output:
[]
3. Different Result Types
The expression determines what type of value is stored in the resulting list. Therefore, the new list can contain strings, numbers, tuples, or other appropriate values.
numbers = [1, 2, 3]
result = [(number, number ** 2) for number in numbers]
print(result)
Output:
[(1, 1), (2, 4), (3, 9)]
Here, the expression creates a tuple for each number, so the resulting list contains tuples.
Common Mistakes
Most beginner mistakes with list comprehension come from misunderstanding the order of its parts. Remembering where the expression, for clause, and condition belong makes the syntax much easier to use.
1. Forgetting the for Clause
A list comprehension needs a for clause to specify where the values come from.
squares = [number ** 2]
This is not a list comprehension. It is an ordinary list containing an expression, and the number must already exist for it to work.
A list comprehension would be:
squares = [number ** 2 for number in numbers]
2. Putting a Filtering if in the Wrong Position
When if is used only for filtering, it must come after the for clause.
even_numbers = [number for number in numbers if number % 2 == 0]
For an if-else expression, the conditional expression appears before the for clause.
result = ["Even" if number % 2 == 0 else "Odd" for number in numbers]
3. Making the Expression Too Complicated
List comprehension is intended to make simple list-building logic clear and concise. If the expression contains too many operations or nested conditions, a traditional for loop may be easier to understand.
Shorter code is not automatically better code. Readability should remain the main consideration.
4. Confusing Filtering with Transformation
A filtering condition controls whether an item is included, while the expression controls what value is stored. These two parts can work together but have different purposes.
squares = [number ** 2 for number in numbers if number % 2 == 0]
Here, the if condition filters the numbers, while number ** 2 determines the value stored in the resulting list.
Important Rules
A few rules cover most everyday uses of list comprehension. Keeping these rules in mind makes it easier to write correct and readable comprehensions.
- List comprehension creates a new list.
- The basic form contains an expression, for, and an iterable.
- A filtering if condition comes after the for clause.
- An if-else expression comes before the for clause.
- The iterable can be a list, tuple, string, range, set, or another iterable.
- Multiple for clauses can be used for nested iteration.
- Multiple filtering conditions can be combined using logical operators.
- Complex logic may be clearer with a traditional for loop.
- The expression determines the values stored in the new list.
Quick Reference
The following patterns cover the most common forms of list comprehension. They can be used as a quick reference when writing or reviewing Python code.
| Purpose | Syntax |
|---|---|
| Basic comprehension | [expression for item in iterable] |
| Filtering | [expression for item in iterable if condition] |
| if-else | [value1 if condition else value2 for item in iterable] |
| Using range() | [expression for item in range(...)] |
| Multiple conditions | [expression for item in iterable if condition1 and condition2] |
| Nested iteration | [expression for item1 in iterable1 for item2 in iterable2] |
Conclusion
List comprehension provides a concise way to create a new list by combining an expression with iteration and, optionally, conditions. It is especially useful for simple transformations and filtering operations.
The most important patterns to understand are the basic form, filtering with if, and choosing values with if-else. Once these patterns are familiar, list comprehension becomes a useful and readable tool for everyday Python programming.
Frequently Asked Questions
1. What is list comprehension in Python?
List comprehension is a concise way to create a new list by applying an expression to items from an iterable, optionally using conditions to filter those items.
2. What is the basic syntax of list comprehension?
[expression for item in iterable]
Example:[number ** 2 for number in numbers] #for squaring the number present in numbers list
3. Can list comprehension contain an if condition?
Yes. An if condition can be used to filter which items are included.
result = [number for number in numbers if number > 0]
4. Can list comprehension use if-else?
Yes. An if-else expression can determine which value is stored for each item.
result = ["Even" if number % 2 == 0 else "Odd" for number in numbers]
5. Does list comprehension modify the original list?
No. A normal list comprehension creates a new list. The original list is not directly modified by the comprehension.
0 Comments