List comprehensions are one of the features that make Python feel different the first time you use it. A job that takes four or five lines with a regular loop collapses into a single readable line. You collect values, transform them, and filter them in one expression, and the result is a brand new list.
That does not mean you should rewrite every loop as a comprehension. It means you have a compact tool for the very common pattern of building a list from another iterable. Once you understand the order of the parts, python list comprehensions become easy to read and easy to write, and you will start spotting places in your own code where a loop is doing more work than it needs to.
This guide walks through the basic syntax, mapping, filtering, if-else expressions, nested loops, and the related dictionary and set forms. If you are also building up your Python basics, the companion notes on working with dictionaries in Python pair well with this one, because the two data types appear together in almost every real script.
The Basic Pattern: From Loop to Comprehension
Start with the loop version. You create an empty list, iterate over some numbers, do something to each one, and append the result. That pattern shows up everywhere: squaring numbers, cleaning strings, extracting a field from a set of records.
squares = []
for n in range(1, 6):
squares.append(n * n)
print(squares) # [1, 4, 9, 16, 25]
The code above creates an empty list called squares. The for loop visits each number from 1 to 5 produced by range. Inside the loop, n * n calculates the square, and append adds it to the list. After the loop finishes, printing the list shows the five squared values in order.
The comprehension version keeps exactly the same logic but rearranges it. The expression you want to collect comes first, then the loop part, all inside square brackets.
squares = [n * n for n in range(1, 6)] print(squares) # [1, 4, 9, 16, 25]
Read this line from the middle outwards. The for n in range(1, 6) part does the iterating, just like the loop before. The n * n at the front is the value that gets collected for each iteration. The brackets tell Python to gather all of those values into a new list and assign it to squares. There is no separate append call because collecting is built into the syntax.
Transforming Values: The Mapping Idea
The front expression can be any valid Python expression involving the loop variable. That makes comprehensions a clean way to transform data: strip whitespace from strings, convert types, or pull one field out of a larger structure.
names = [" ada ", "GRACE", "Linus "] clean = [name.strip().title() for name in names] print(clean) # ['Ada', 'Grace', 'Linus']
Here the expression is name.strip().title(). For each raw string in names, strip removes leading and trailing spaces, and title converts the result to title case with the first letter capitalised. The comprehension collects the cleaned versions into a new list, while the original list stays untouched. That separation matters when other parts of your program still need the original values.
The same approach works for converting data you have read from a file or a form. Prices stored as strings become floats, or a list of dictionaries becomes a list of just the names.
prices = ["9.99", "24.50", "3.75"] amounts = [float(p) for p in prices] total = sum(amounts) print(total) # 38.24
In this example float(p) converts each string to a number. Without that conversion, adding the values would join the strings together instead of adding them. Once you have a list of floats, the built-in sum function can total them. If reading data in the first place is new to you, the notes on reading and writing files in Python show how that text usually arrives in a script.
Filtering With an If Clause
Often you do not want every item. You want only the even numbers, only the active users, only the words longer than three letters. A comprehension can filter by adding an if clause at the end. Items that fail the test are simply left out.
numbers = [3, 8, 12, 5, 20, 7, 14] evens = [n for n in numbers if n % 2 == 0] print(evens) # [8, 12, 20, 14]
The new part is if n % 2 == 0 at the end. The modulo operator % gives the remainder after division, so a remainder of zero means the number is even. Python evaluates that test for each item. Only items where the test is true contribute their value to the result. The expression at the front stays plain n because we keep the number itself unchanged.
Filtering strings works the same way, and combining a transformation with a filter is common in data cleaning code.
words = ["cat", "elephant", "dog", "giraffe", "ant"] long_words = [w.upper() for w in words if len(w) > 3] print(long_words) # ['ELEPHANT', 'GIRAFFE']
Here len(w) > 3 keeps only words with more than three characters. The surviving words are converted with upper before being collected. Notice the order of evaluation: Python iterates, tests the condition, and only then computes the front expression for the items that pass. That is why filtering is efficient as well as short. You do not waste work transforming items you are going to discard.
You can also combine conditions with and or or when a single test is not enough, for example keeping scores that are at least 50 and at most 90 with a condition such as s >= 50 and s <= 90.
Choosing Between Two Values: If-Else at the Front
The filtering if at the end drops items. Sometimes you want to keep every item but change the value depending on a condition. That is a different job, and it uses a conditional expression placed at the front, before the for part. The syntax looks similar, so this distinction trips up many learners.
numbers = [1, 2, 3, 4, 5] labels = ["even" if n % 2 == 0 else "odd" for n in numbers] print(labels) # ['odd', 'even', 'odd', 'even', 'odd']
The front expression here is a full conditional: “even” if n % 2 == 0 else “odd”. For every number, Python picks one of the two strings. Nothing is dropped, so the result has the same length as the input. Compare that with the filtering form, where the if sits after the for clause and has no else part. Position is the clue: if-else before for means choose a value, if after for means keep or skip.
A practical use is normalising data, for example replacing missing values with a default using an expression such as r if r is not None else 0, which prevents errors when arithmetic later meets None.
Nested Loops Inside a Comprehension
A comprehension can contain more than one for clause. The classic example is flattening a list of lists, such as rows of a table, into a single list. The order of the for clauses matches the order you would write in nested loops: outer loop first, inner loop second.
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] flat = [value for row in matrix for value in row] print(flat) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
The first for clause iterates over the rows of the matrix. The second for clause iterates over the values inside the current row. The front expression is just value, so each inner value is collected in order. If you are unsure about the order, write the equivalent nested loop and read the for lines top to bottom; the comprehension lists them left to right in the same sequence.
Nesting is also the point where comprehensions can go too far. Two for clauses are usually fine. Three levels, or a long condition added on top, often reads better as a regular loop. Readability is the deciding factor, not line count.
Dictionary and Set Comprehensions
The same idea extends to dictionaries and sets. A dictionary comprehension uses curly braces and a key: value expression at the front. A set comprehension also uses curly braces but with a single expression, and it automatically removes duplicates.
names = ["ada", "grace", "linus"]
lengths = {name: len(name) for name in names}
print(lengths) # {'ada': 3, 'grace': 5, 'linus': 5}
Here name is the key and len(name) is the value. Each iteration adds one pair to the new dictionary. This pattern is handy for building lookup tables, counting, or inverting a mapping. For more operations like merging, safe lookups, and updating, keep the Python dictionary tips close by, since comprehensions handle creation while methods handle the rest of the work.
letters = "banana"
unique = {ch for ch in letters}
print(sorted(unique)) # ['a', 'b', 'n']
The set comprehension collects each character of the string, and because a set stores each value once, duplicates disappear. Sorting the result for display gives a clean list of the distinct characters. This is a quick way to find the unique items in any iterable when order does not matter.
Dictionary comprehensions can include a filter too, for example {item: qty for item, qty in stock.items() if qty > 0} to copy only items with positive stock. Unpacking pairs inside a comprehension is a pattern you will use often with real data.
When to Use a Regular Loop Instead
Comprehensions build lists. If your loop does not build a list, a comprehension is probably the wrong tool. Printing each line of a file, writing to a database, or updating several variables involves side effects, and forcing those into a comprehension makes the code harder to follow and can create a list of None values that nobody uses.
Long expressions are another signal. If the front expression wraps across lines or the condition needs a comment to explain it, a plain loop with a few statements will serve the next reader better. Many style guides suggest that a comprehension should fit comfortably on one line, or at most two when formatted carefully.
There is also a middle path: extract the transformation into a small named function and call it inside the comprehension, for example [clean_email(e) for e in emails] where clean_email strips and lowercases one address. The comprehension stays short, the rules live in one place, and the same approach works when reshaping data fetched with the Requests library.
Common Mistakes to Avoid
The most common mistake is putting the condition in the wrong place. A filtering if goes at the end with no else. An if-else choice goes at the front as part of the expression. Mixing the two produces either a syntax error or a result you did not expect, so check the position first when a comprehension misbehaves.
Another frequent issue is reusing the same variable name in confusing ways while building a comprehension. Give the result a clear new name, and assign it back only if replacing the data is truly intended.
Conclusion
Python list comprehensions turn the everyday pattern of looping, transforming, and filtering into a single clear expression. Keep the structure in mind: value first, loop second, optional filter last, and reach for if-else at the front when you need to choose between values rather than drop items. Used where they fit, and replaced by a plain loop where they do not, comprehensions will make your Python shorter without making it harder to understand.
Tagged: python coding tips python filtering python list comprehensions python lists python loops python snippets



3 thoughts on “Python List Comprehensions: Cleaner Loops With Examples”