Python course module guide: Data structures and expressions
Python list comprehensions provide a compact way to build a new list from an iterable. They are excellent for small transformations and filters, but a shorter expression is not automatically a clearer expression.
What you will learn
- Write transformation and filtering comprehensions.
- Distinguish filters from conditional expressions.
- Build dictionary and set comprehensions.
- Know when a normal loop is more readable.
List comprehension syntax
The basic shape is [expression for item in iterable]. The expression describes the value placed in the new list, while the loop supplies each source item.
prices = [120, 250, 80, 400]
prices_with_tax = [round(price * 1.18, 2) for price in prices]
This produces a new list and leaves the original untouched. That makes the data flow easier to reason about than code that silently changes shared state. For the behavior of lists, tuples, sets and dictionaries, use the practical Python data structures guide.
Filter items with a trailing if
scores = [38, 72, 91, 44, 67]
passing_scores = [score for score in scores if score >= 50]
The trailing if decides whether an item enters the result. It does not provide an alternative value. Use it when unwanted rows should disappear.
Use a conditional expression for two outcomes
labels = ["pass" if score >= 50 else "retry" for score in scores]
Here every score produces one output. The if/else sits before the for because it is part of the expression. Beginners often confuse this with a filter; ask whether the result should keep every input or remove some inputs.
Call small functions from comprehensions
def normalize_name(value: str) -> str:
return " ".join(value.strip().title().split())
raw_names = [" anita rao", "RAVI kumar", " meena "]
clean_names = [normalize_name(name) for name in raw_names]
A named function keeps the comprehension focused on data flow. The function can be tested separately and reused. Review Python parameters, return values and scope if the function boundary is unclear.
Dictionary and set comprehensions
students = [
{"id": 101, "name": "Asha"},
{"id": 102, "name": "Kiran"},
]
name_by_id = {student["id"]: student["name"] for student in students}
unique_words = {word.lower() for word in ["Python", "API", "python"]}
A dictionary comprehension needs both a key and a value. A set comprehension is useful when uniqueness is the goal. If duplicate keys occur in a dictionary comprehension, the later value wins, so validate source data when duplicates would indicate an error.
Nested loops: read from left to right
teams = [["Asha", "Ravi"], ["Meena", "John"]]
members = [name for team in teams for name in team]
The loop order matches the equivalent nested for statements. One extra level can be reasonable. Multiple conditions and several nested loops usually deserve a normal loop or helper function.
List comprehension vs generator expression
Square brackets build the full list immediately. Parentheses create a generator expression that yields items when requested. A list is useful when you need indexing, repeated passes or the complete result. A generator is useful for a one-pass pipeline or a large stream. Continue with Python iterators and generators to understand lazy evaluation.
Readability rules
- Keep the expression and condition short enough to scan.
- Move complex calculations into a named function.
- Avoid side effects such as printing or updating external lists.
- Do not reuse a comprehension only to appear clever.
- Use meaningful names instead of single letters outside simple mathematics.
Practical cleaning example
records = ["101,Asha,82", "", "102,Ravi,74", "bad row"]
valid_rows = [row.split(",") for row in records if row.count(",") == 2]
result = [
{"id": int(student_id), "name": name, "score": int(score)}
for student_id, name, score in valid_rows
]
This demonstrates transformation and filtering, but production code should report bad rows instead of silently discarding them. For structured tabular analysis, the later pandas GroupBy and merge project provides stronger validation and reconciliation checks.
Practice checklist
Rewrite one simple loop as a list comprehension, one filter as a trailing if, and one two-outcome mapping with a conditional expression. Then reverse the exercise: convert a complicated comprehension into a readable loop. The ability to choose clarity is more important than memorizing syntax.
List comprehension FAQs
Are comprehensions always faster than loops?
They can be efficient for simple construction, but performance depends on the operation and data. Choose readability first and measure only when speed actually matters.
Can a comprehension modify an existing list?
Its normal purpose is to create a new collection. Using it only for side effects wastes the result and hides intent; use a regular loop for actions.
How long should a comprehension be?
There is no useful character limit. If a reader cannot identify the transformation, iteration and filter quickly, extract a function or write a loop.
Official reference: Python tutorial on list comprehensions.
Learn Python with guided practice in Visakhapatnam
These concepts become useful when you apply them in exercises, assignments and reviewed projects. Explore Python training in Vizag for the complete curriculum, classroom and online learning options, and current batch details.
Python module learning path
Continue through the related practical guides in this course-module series: