Back to Python Mastery
AdvancedAdults

List Comprehensions

List comprehensions provide a concise way to create lists. They are often more readable and more performant than using a standard for loop.

Suppose you want to create a list of squares from 0 to 9. A standard for loop would look like this:

squares = []
for x in range(10):
squares.append(x**2)

With a list comprehension, you can achieve the same result in a single line:

squares = [x**2 for x in range(10)]

The structure is: [expression for item in iterable].

You can also add a condition to filter the list. Let's get the squares of only the even numbers:

even_squares = [x**2 for x in range(10) if x % 2 == 0]

This is equivalent to:

even_squares = []
for x in range(10):
if x % 2 == 0:
even_squares.append(x**2)

List comprehensions are a hallmark of idiomatic Python code.

Filter a List

Given a list of numbers, use a list comprehension to create a new list containing only the numbers greater than 10.