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.
Here's the pattern a comprehension shortens:
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 same result in one line:
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.
Every list comprehension follows the same skeleton:
[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.
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.
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.