List Comprehension
List Comprehension
Introduction
List comprehension is a concise and Pythonic way of generating lists. It allows you
to construct a new list by applying an expression to each element of an existing
iterable. This expression can also include conditional statements, making it a
powerful tool for filtering elements based on certain criteria.
Using list comprehension not only simplifies your code but also improves its
readability. It is widely used by Python developers to create lists in a more
elegant and efficient manner.
Code
script.py
1
2
3
4
5
"""
Create a list of squares of numbers from 1 to 5
"""
squares = [x**2 for x in range(1, 6)]
print(squares) # Output: [1, 4, 9, 16, 25]
Execute code
Basic List Comprehension with Conditionals
List comprehension allows you to include conditionals, which help filter elements
based on certain conditions. You can use the if statement to include only those
elements that satisfy the specified condition.
Example:
Code
script.py
1
2
3
4
5
"""
Create a list of even numbers from 1 to 10
"""
even_numbers = [x for x in range(1, 11) if x % 2 == 0]
print(even_numbers) # Output: [2, 4, 6, 8, 10]
Execute code
Nested List Comprehensions
List comprehensions can also be nested, allowing you to create more complex lists.
You can have one or more for loops and conditionals within the list comprehension.
Example:
Code
script.py
1
2
3
4
5
6
7
"""
Create a list of tuples containing all pairs of numbers from two separate lists
"""
list1 = [1, 2, 3]
list2 = [10, 20]
pairs = [(x, y) for x in list1 for y in list2]
print(pairs) # Output: [(1, 10), (1, 20), (2, 10), (2, 20), (3, 10), (3, 20)]
Execute code
Using List Comprehension with Built-in Functions like map() and filter()
List comprehension can be combined with built-in functions like map() and filter()
to perform more advanced operations on lists.
Example:
Code
script.py
1
2
3
4
5
6
7
8
9
10
11
12
13
"""
Use map() with list comprehension to apply a function to each element
"""
numbers = [1, 2, 3, 4, 5]
squared_numbers = [x**2 for x in numbers]
print(squared_numbers) # Output: [1, 4, 9, 16, 25]
"""
Use filter() with list comprehension to include only certain elements
"""
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = [x for x in numbers if x % 2 == 0]
print(even_numbers) # Output: [2, 4, 6]
Execute code
Performance Considerations and Use Cases for List Comprehension
List comprehension is generally faster and more efficient compared to traditional
loops when dealing with simple operations on lists. However, for complex and
memory-intensive operations, list comprehension might not be the best choice.
Performance Considerations: