Python

Basic List Comprehension

List Comprehensions

List comprehensions create lists in one line.

Traditional Way

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

With List Comprehension

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

[0, 1, 4, 9, 16]

Syntax

[expression for item in iterable]

Your Task

Create a list of the first 10 positive integers doubled (2, 4, 6, ..., 20) using a list comprehension. Print the result.

script.py
Loading PYTHON engine...
Downloading Python… (one-time, ~10 MB)

Downloading Python… (one-time, ~10 MB)

This runs entirely in your browser and is cached for next time.