List comprehensions provide a concise way to create lists in Python. They consist of brackets containing an expression followed by a for
clause, and can include optional if
clauses.
Basic Syntax
new_list = [expression for item in iterable]
Example: Creating a List of Squares
squares = [x**2 for x in range(1, 6)]
print(squares) # Output: [1, 4, 9, 16, 25]
Adding an if Condition
You can include an if
condition to filter items:
even_squares = [x**2 for x in range(1, 11) if x % 2 == 0]
print(even_squares) # Output: [4, 16, 36, 64, 100]
Nesting List Comprehensions
Create a list of tuples:
pairs = [(x, y) for x in range(3) for y in range(3)]
print(pairs)
Using Functions in Expressions
def double(x):
return x * 2
doubled = [double(x) for x in range(5)]
print(doubled) # Output: [0, 2, 4, 6, 8]
Conclusion
List comprehensions offer a readable and efficient way to create lists. They are a powerful feature in Python that can simplify your code.