What is list comprehension?
List comprehension is a concise and elegant way to create lists in Python. It offers a more compact syntax than traditional for loops and often improves readability and performance.
What is List Comprehension?
List comprehension in Python provides a shorter syntax to create new lists based on existing iterables (like lists, tuples, strings, etc.). It filters and transforms elements in a single line of code, making it more 'Pythonic' than many other approaches.
Basic Syntax
new_list = [expression for item in iterable]
Here, expression is the operation performed on each item, and iterable is the source collection. The result of the expression for each item is collected into new_list.
Equivalent Loop
A list comprehension can often replace a multi-line for loop that appends items to a list.
squares = []
for i in range(1, 6):
squares.append(i**2)
# Equivalent list comprehension:
# squares = [i**2 for i in range(1, 6)]
Why Use List Comprehension?
- Conciseness: Reduces boilerplate code compared to traditional loops.
- Readability: Can be easier to read and understand the intent of the code for simple transformations.
- Performance: Often faster than a traditional for loop for creating lists, as it is optimized internally in CPython.
With Conditional Logic
You can include an if clause to filter items from the iterable.
even_numbers = [x for x in range(10) if x % 2 == 0]
# even_numbers will be [0, 2, 4, 6, 8]
Nested List Comprehensions
List comprehensions can be nested, similar to nested for loops, to work with multi-dimensional data structures like matrices.
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [num for row in matrix for num in row]
# flattened will be [1, 2, 3, 4, 5, 6, 7, 8, 9]
Conclusion
List comprehensions are a powerful and idiomatic feature in Python for creating lists efficiently and expressively. Mastering them is key to writing clean and performant Python code for list manipulation.