Skip to main content

List Comprehension

Building Lists the Pythonic Way

· 3 min read

In the previous unit, we learned how to create and manipulate lists. Now let's look at list comprehension, a concise way to generate lists in a single line.

List Comprehension

What Is List Comprehension?

List comprehension creates a new list by applying an expression to each item in an existing iterable. It's more compact than writing a for loop to build a list.

Here's a simple example:

squares = [x**2 for x in range(10)]
print(squares) # Outputs: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

This creates a list of squares for numbers 0 through 9. The expression x**2 runs for each value of x in the range.

The Syntax

The basic form is:

[expression for item in iterable]

The expression is what you want in the new list. The item takes each value from the iterable. Python evaluates the expression for every item and collects the results into a new list.

Compare this to the equivalent for loop:

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

The list comprehension does the same thing in one line.

Adding Conditions

You can filter which items get included by adding an if clause:

even_squares = [x**2 for x in range(10) if x % 2 == 0]
print(even_squares) # Outputs: [0, 4, 16, 36, 64]

This only squares the even numbers. The condition x % 2 == 0 filters out odd values before the expression runs.

Project: Pattern Generator

Let's use list comprehension to generate movement instructions for Turtle. Each instruction is a tuple of distance and angle.

import turtle

screen = turtle.Screen()
screen.setup(width=800, height=600)
screen.bgcolor("white")

t = turtle.Turtle()

# Generate alternating short and long movements
movements = [(50, 90) if i % 2 == 0 else (100, 90) for i in range(36)]

for move in movements:
t.forward(move[0])
t.right(move[1])

t.hideturtle()
turtle.done()

The list comprehension creates 36 tuples. When i is even, the tuple is (50, 90), meaning move 50 pixels and turn 90 degrees. When i is odd, it's (100, 90), meaning move 100 pixels and turn 90 degrees. The alternating distances create an interesting pattern.

The for loop then executes each movement. We access the first element with move[0] for distance and move[1] for angle.

Try changing the expression to create different patterns. Vary the angles, add more conditions, or use different ranges.

In the next unit, we'll explore ranges, sets, and tuples, more ways to organize data in Python.