Skip to content
On this page

List Comprehension:

List comprehensions provide a concise way to create lists.

python
# List comprehension
numbers = [x for x in range(1, 6)]   # [1, 2, 3, 4, 5]
squares = [x ** 2 for x in numbers]  # [1, 4, 9, 16, 25]

Set Comprehension:

python
# Set comprehension
numbers = {x for x in range(1, 6)}   # [1, 2, 3, 4, 5]
squares = {x ** 2 for x in numbers}  # [1, 4, 9, 16, 25]