Next →

What is a List Comprehension?

A list comprehension is a concise way to create a new list by applying an expression to each item in an existing list.

Example:

numbers = [1, 2, 3, 4, 5]
squares = [n**2 for n in numbers]
print(squares)  # Output: [1, 4, 9, 16, 25]

Why Use List Comprehensions?

They make your code shorter and often easier to read when creating or transforming lists.

Adding a Condition

You can also add a condition to include only items that meet a certain requirement.

Example:

even_squares = [n**2 for n in numbers if n % 2 == 0]
print(even_squares)  # Output: [4, 16]