Tsallaka zuwa abun ciki
Justice Tech School

List Comprehensions

A comprehension builds a list in one line: [expr for x in items if cond]. Dict and set versions use braces.

Example
sq = [n * n for n in range(6) if n % 2 == 0]
print(sq)
print({c: ord(c) for c in "ab"}, {x % 3 for x in range(10)})

Result

[0, 4, 16]
{'a': 97, 'b': 98} {0, 1, 2}

Exercise

Squares.

[n  2 for n in a]

Quiz Test

What does an if at the end do?

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