Tsallaka zuwa abun ciki
Justice Tech School

List Comprehension

A list comprehension has the form [expression for item in iterable if condition]. It is a short, readable way to transform or filter a list. If it becomes long or hard to read, use a normal for loop.

Example
nums = [1, 2, 3, 4, 5, 6]
squares = [n * n for n in nums]
print(squares)
evens = [n for n in nums if n % 2 == 0]
print(evens)
words = ["hi", "python", "ok"]
print([w.upper() for w in words if len(w) > 2])

Result

[1, 4, 9, 16, 25, 36]
[2, 4, 6]
['PYTHON']

Exercise

Complete the comprehension.

[n * 2  n in [1, 2, 3]]

Quiz Test

What does [n for n in range(3)] produce?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.