LESSON · 1 OF 5

List comprehensions

List comprehensions

A list comprehension builds a new list from an existing collection in one line. It replaces the very common pattern of creating an empty list and appending to it in a loop.

The long way

Here's the pattern a comprehension shortens:

python
names = ["web-01", "db-01"]
upper = []
for name in names:
    upper.append(name.upper())

Three lines of setup and loop just to transform each item.

The comprehension

The same result in one line:

python
upper = [name.upper() for name in names]

Read it left to right: for each name in names, produce name.upper(), and collect the results into a new list. The expression on the left is what each item becomes; the for part on the right is where the items come from.

The shape

Every list comprehension follows the same skeleton:

python
[expression for item in collection]

The expression runs once per item and its result goes into the new list. The original collection is left untouched.

Why use them

Comprehensions are shorter and, once the shape is familiar, easier to read than the loop-and-append version. In DevOps scripts you'll use them constantly to turn one list into another: hostnames into URLs, raw strings into integers, paths into filenames. When the transform is simple, a comprehension says it in one clear line.

Keep them simple

A comprehension is best for a straightforward transform. If the logic needs several steps or branching, a plain for loop stays more readable. Reach for a comprehension when the line stays short and obvious.

Spin up a fresh environment and practice live.
python-devops · fresh machine · ready in under a minute