Python – List Comprehension
A list comprehension is a concise and efficient way to create a new list by iterating over existing iterables, such as lists, tuples, or sets. It combines looping, conditional filtering, and expression evaluation into a single line of code.
Syntax
[expression for item in iterable if condition]
Components
1. Expression:
- Defines the value to include in the new list.
- It can be a simple variable, a function call, or any valid Python expression
2. for item in iterable
:
- The loop that iterates through each element in the
iterable
.
3. item
:
- Represents the current element being processed in the iteration.
4. iterable
:
- The source sequence (like a list, tuple, set, or range) from which elements are drawn.
5. if condition
(optional):
- A filter to include only elements that meet the specified condition.
- The condition must be evaluated to
True
for the element to be added to the new list.
The syntax [expression for item in iterable if condition]
creates a new list by evaluating the expression
for each item
in the iterable
that satisfies the optional condition
.
Example:
Let’s say you have a list of numbers and you want to create a new list with the squares of each number. Here is how you can do it using both a traditional for
loop and list comprehension:
Using a traditional for loop
numbers = [1, 2, 3, 4]
squares = []
for number in numbers:
squares.append(number ** 2)
print(squares) # Output: [1, 4, 9, 16]
Using list comprehension
numbers = [1, 2, 3, 4]
squares = [number ** 2 for number in numbers]
print(squares) # Output: [1, 4, 9, 16]
As you can see from the above example, list comprehension provides a more concise and readable way to create a list of squares compared to the traditional for
loop.
Conditional logic with list comprehension
You can also include if
conditions within a list comprehension to filter elements from the original iterable.
Example:
Let’s create a list of even numbers from a given range.
even_numbers = [x for x in range(10) if x % 2 == 0]
print(even_numbers) # Output: [0, 2, 4, 6, 8]
Numbers that are completely divisible by 2, meaning x % 2 == 0
are even numbers.
if else in list comprehension
You can also use if-else
within the expression part of the list comprehension.
Example:
Let’s classify numbers as “even” or “odd” using if-else with list comprehension
numbers = [1, 2, 3, 4]
even_odd_labels = ["even" if number % 2 == 0 else "odd" for number in numbers]
print(even_odd_labels) # Output: ['odd', 'even', 'odd', 'even']
Nested list comprehension
List comprehension can also be nested to work with nested lists and multi-dimensional data.
Example: Extracting even numbers from a 2D list
Let’s say you have a 2D list, and you want to create a new list containing only the even numbers from it.
# A 2D list
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# Extracting even numbers using nested list comprehension
even_numbers = [num for row in matrix for num in row if num % 2 == 0]
print(even_numbers) # Output: [2, 4, 6, 8]
The outer loop for row in matrix
iterates over each row in the 2D list.
The inner loop for num in row
iterates over each number in the current row.
The if num % 2 == 0
condition ensures that only even numbers are included in the final list.