PyForge ยท Python practice library
All topics

Topic 14 of 17

Comprehensions

Build lists, sets, and dicts in one expressive line.

List comp
Set comp
Dict comp
Nested comp

Basic

1 program

Program 1

List comprehension

Basic

Squares from 1 to 10.

python
squares = [x ** 2 for x in range(1, 11)]
print(squares)

Intermediate

2 programs

Program 1

Conditional comprehension

Intermediate

Filter while building.

python
nums = range(1, 21)
div_3_or_5 = [n for n in nums if n % 3 == 0 or n % 5 == 0]
print(div_3_or_5)

Program 2

Dict & set comprehensions

Intermediate

Construct dicts and sets concisely.

python
chars = "mississippi"
count = {c: chars.count(c) for c in set(chars)}
print(count)

Advanced

1 program

Program 1

Nested comprehension (flatten)

Advanced

Flatten a 2-D list.

python
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [n for row in matrix for n in row]
print(flat)