List comprehension in Python is a concise and readable way to create new lists by applying an expression to each item in an existing iterable (like a list, tuple, or range), optionally filtering elements with a condition. It replaces verbose for loops and .append() calls with a single line of code.
Basic Syntax
[expression for item in iterable]expression: The operation applied to each item (e.g.,
x ** 2,word.upper()).item: A variable representing each element in the iterable.
iterable: The source data (e.g.,
range(10),['a', 'b', 'c']).
With Filtering (if condition)
[expression for item in iterable if condition]Only items satisfying the condition are included.
Examples
Square numbers from 0 to 9:
squares = [x ** 2 for x in range(10)] # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]Filter even numbers:
evens = [x for x in range(10) if x % 2 == 0] # Output: [0, 2, 4, 6, 8]Capitalize words with more than 3 letters:
words = ["fox", "giraffe", "rat", "zebra", "owl"] long_words = [word.upper() for word in words if len(word) > 3] # Output: ['GIRAFFE', 'ZEBRA']
Advanced Features
Nested loops (e.g., flattening a 2D list):
matrix = [[1, 2], [3, 4]] flat = [num for row in matrix for num in row] # Output: [1, 2, 3, 4]Conditional expressions (if/else):
result = ["even" if x % 2 == 0 else "odd" for x in range(5)] # Output: ['even', 'odd', 'even', 'odd', 'even']Using
enumerate():fruits = ['apple', 'banana'] indexed = [f"{i}: {f}" for i, f in enumerate(fruits)] # Output: ['0: apple', '1: banana']
Performance & Best Practices
Faster than equivalent for loops due to internal optimizations in Python.
More readable and concise than traditional loops.
Avoid overly complex comprehensions — if it exceeds 80–100 characters or contains multiple nested conditions, use a regular loop for clarity.
For large datasets, use generator expressions
( )instead of list comprehensions[ ]to save memory.
When to Use
Creating transformed or filtered lists.
Replacing simple for loops with
.append().Writing "Pythonic" code that is both efficient and readable.
Alternatives
map()andfilter(): Functional approach, less readable for beginners.Generator expressions: Use
()for memory efficiency with large datasets.Regular loops: Best for complex logic or debugging.
List comprehensions are a core Python feature that enhances code clarity and performance for common list creation tasks.
Python list function or list comprehension - Stack Overflow
Is there an official name for a list comprehension with multiple for clauses?
Understanding the need for list comprehension
Does anyone else hate list comprehension?
Videos
Even Chat-GPT and my dog can't explain it right. I think I might be unintelligent.
There is a slight bit of difference in their performance as can be seen from the following:
squares1 = [x**2 for x in range(1, 11)]
3.07 µs ± 70 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
squares2 = list(x**2 for x in range(1, 11))
3.65 µs ± 35.6 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
this can primarily be because in case 1 you are iterating and generating values for the list at the same time.
In case 2 you are generating values while iterating and then at the end of it converting the same to a list and this is then stored as a given variable.
I way I see it, first program directly initializes squares1 as a list through list comprehension.
The other one first creates a generator class object and then converts it into a list. I think first approach is more efficient.
There are little differences between lists and generators but as per my knowledge and experience lists do the job faster and generators do it lazily yielding single result for every iteration. For most of your tasks, I'd recommend opting for lists.
Im not sure if this concept of list comprehension is a super common thing among developers ( but then again I am just starting to learn python ) but I was wondering how important is it in the job field. Do i really need to be able to write my own programs using proper list comprehension notation or is it fine if I stick to the usual way I iterate through lists with a traditional for loop set up.
P.S this is what I mean by list comprehension:
def elementwise_greater_than(L, thresh):
return [ele > thresh for ele in L]
This is a way is a bit harder for me to read and understand so I was wondering if in the actual job market and stuff emplpoyees are expected to understand it like that?