Member-only story
List comprehensions are a concise and expressive way to create lists in Python. They provide a compact syntax for generating lists by applying an expression to each item in an iterable (such as a list, tuple, or range) and optionally filtering the items based on a condition. List comprehensions are a fundamental feature of Python and are considered Pythonic due to their readability and efficiency.
The basic syntax of a list comprehension is as follows:
[expression for item in iterable if condition]
expression
: The expression to evaluate and include in the new list.item
: The variable representing each element in the iterable.iterable
: The source of elements to iterate over.condition
(optional): A filter that determines whether to include the item in the new list.
1. Create a list of squares:
squares = [x**2 for x in range(10)]
# Result: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
2. Filter even numbers:
evens = [x for x in range(10) if x % 2 == 0]
# Result: [0, 2, 4, 6, 8]
3. Flatten a 2D list:
matrix = [[1, 2, 3], [4, 5…