Creating Lists in One Line
List comprehensions combine iteration and transformation into a single expression, making code concise and readable.
numbers = [1, 2, 3, 4, 5]
squares = [n * n for n in numbers]
print(squares)
Filtering with Conditions
You can add conditions to comprehensions to filter items, which is powerful for data selection.
even = [n for n in numbers if n % 2 == 0]
print(even)
Transforming Strings
Comprehensions can transform text, like converting names to uppercase, making them versatile beyond numbers.
names = ["alice", "bob", "carol"]
uppercase_names = [name.upper() for name in names]
print(uppercase_names)
My Take
List comprehensions combine iteration, transformation, and filtering into one concise expression.
Top comments (0)