Python Tutorial
Python List Comprehension
A shorter syntax to create a new list from an existing iterable, with an optional filter.
The Syntax
newlist = [expression for item in iterable if condition]
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x for x in fruits if "a" in x]
print(newlist)Expression
The expression is the current item, which you can transform.
fruits = ["apple", "banana", "cherry"]
print([x.upper() for x in fruits])
print([x if x != "banana" else "orange" for x in fruits])
print([n for n in range(10) if n < 5])📘 Real-World Deep Dive
List comprehensions consolidate a "build by transforming" into a single readable expression, and they're compiled in CPython into a fast bytecode loop — often 2-3× faster than an equivalent <code>for</code> loop.
Real-Life Scenario
Build a flat list of "title-case tags" from messy raw user input, dropping empty / too-short entries in one pass.
Real-Life Example
raw = [
" python ",
"Data-Science",
" ",
"AI/ML",
"Web3",
"x", # too short
"backend",
]
def clean_tags(tags: list[str], min_len: int = 2) -> list[str]:
return [
t.strip().title()
for t in tags
if t.strip() and len(t.strip()) >= min_len
]
print(clean_tags(raw))Expected Output
['Python', 'Data-Science', 'Ai/Ml', 'Web3', 'Backend']Common mistakes
- Nested comprehensions past two levels hurt readability; refactor into helper functions.
- Calling a slow function inside the comprehension fires once per element — precompute outside if possible.
- Forgetting to break a comprehension across multiple lines makes diffs painful; one predicate per line.
🚀 Performance & Best Practices
- Use generator expressions
(...)instead of[...]when you only iterate — saves memory for large inputs. sum(1 for x in xs if cond)is slightly faster thanlen([x for x in xs if cond])for huge inputs.- If you need both the index and the value, prefer
enumerate(xs)overrange(len(xs)).
🧪 Try It Yourself
- Add a
max_tagsargument toclean_tagsthat truncates to the longest entries by length. - Stop the bad habit: rewrite
clean_tagsusing a generator and pass it tolist(...). - Chain two comprehension passes into a single comprehension and benchmark both.