List Comprehensions
List comprehensions are a concise and powerful way to create lists in Python. They allow you to generate lists by applying an expression to each item in an iterable (e.g., a list, tuple, or range) and optionally filtering the items based on a condition. This section covers the basics of list comprehensions and demonstrates their usage.
1. Basic List Comprehension
The basic syntax of a list comprehension consists of square brackets enclosing an expression followed by a for
clause.
# Create a list of squares of numbers from 0 to 4
squares = [x ** 2 for x in range(5)]
In this example, the expression x ** 2
is applied to each item in the iterable range(5)
, which generates numbers from 0 to 4.
2. List Comprehension with Condition
You can include an optional condition in a list comprehension to filter the items from the source iterable.
# Create a list of even numbers from 0 to 9
evens = [x for x in range(10) if x % 2 == 0]
In this example, the condition x % 2 == 0
filters out odd numbers, resulting in a list of even numbers.
3. Nested List Comprehensions
You can use nested list comprehensions to create lists of lists.
# Create a 3x3 identity matrix using a nested list comprehension
identity_matrix = [[1 if i == j else 0 for i in range(3)] for j in range(3)]
Nested list comprehensions are a powerful tool for generating complex data structures.
4. List Comprehension vs. Traditional Loop
List comprehensions are often more concise and expressive than using traditional for
loops to generate lists.
Here's an example of generating a list of squares using a traditional for
loop:
squares = []
for x in range(5):
squares.append(x ** 2)
And the same task accomplished using a list comprehension:
squares = [x ** 2 for x in range(5)]
List comprehensions make the code more readable and reduce the number of lines.
5. Benefits of List Comprehensions
- Conciseness: List comprehensions provide a compact and readable way to generate lists.
- Efficiency: List comprehensions are generally faster than equivalent
for
loops because they are optimized for speed. - Clarity: List comprehensions express the creation of lists directly from data, making the code easier to understand.
List comprehensions are a valuable feature in Python for creating lists from iterables, applying expressions, and filtering items. They make code cleaner and more expressive.