AnyCompiler

List Comprehensions

A list comprehension builds a new list by describing what each item should become, in a single readable line. Most Python developers reach for this instead of map()/filter() with a lambda — it's considered more idiomatic and, once you're used to the syntax, more readable.

numbers = [1, 2, 3, 4, 5]
squared = [x * x for x in numbers]
print(squared)

evens = [x for x in numbers if x % 2 == 0]
print(evens)
Output
[1, 4, 9, 16, 25]
[2, 4]

[x * x for x in numbers] reads almost like English: "x times x, for every x in numbers." Adding if x % 2 == 0 at the end filters which items get included — this is the exact same result as the map()/filter() example from the previous lesson, in a form most Python code actually uses.

Next: exception handling — dealing with errors gracefully instead of letting your program crash.

Practice exercise

Use a list comprehension to build a list of the cubes of the numbers 1 through 4, then print it.