DEV Community

Cover image for List Comprehensions: Writing Cleaner, Faster Python Code
Mary Nyandia
Mary Nyandia

Posted on

List Comprehensions: Writing Cleaner, Faster Python Code

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)

Enter fullscreen mode Exit fullscreen mode

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)

Enter fullscreen mode Exit fullscreen mode

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)

Enter fullscreen mode Exit fullscreen mode

My Take
List comprehensions combine iteration, transformation, and filtering into one concise expression.

Top comments (0)