List comprehension is a quick way to create a new list by looping through an existing one in a single line of code. Instead of writing several lines with a for
loop and append()
, list comprehension lets you do it all in one go.
It’s useful when you want to build a list from another list or range, especially when you want to apply a change or filter at the same time. For example, you can make a list of squares or pick only even numbers, all in a short and readable way.
Think of it like a mini loop packed into a single line: it does the job of for
and append()
together.
Basic Syntax
The basic format of a list comprehension in Python looks like this:
[expression for item in iterable]
Here:
expression
is what you want to do with each item.item
is a variable name for each element in the list (or any iterable).iterable
is the original list, range, or anything you can loop through.
For example, here’s how you can create a list of squares from 1 to 5:
squares = [x * x for x in range(1, 6)]
print(squares)
This code goes through numbers 1 to 5, multiplies each number by itself, and stores the results in a new list called squares
.
Adding Conditions
List comprehension isn’t just for copying or changing values—you can also filter or transform values using if
and if-else
.
Using if
to Filter Items
You can add an if
at the end of your list comprehension to only include items that meet a condition.
For example, to include only even numbers from 1 to 10:
evens = [x for x in range(1, 11) if x % 2 == 0]
print(evens)
This goes through numbers 1 to 10 and keeps only the even ones.
Using if-else
in the Expression
You can also use if-else
inside the expression part to change each item based on a condition.
For example, let’s label even numbers as "Even"
and odd numbers as "Odd"
:
labels = ["Even" if x % 2 == 0 else "Odd" for x in range(1, 6)]
print(labels)
This returns a new list where each number is replaced with a word based on whether it’s even or odd.
Using range()
with List Comprehension
One of the most common things to do with list comprehension is to create number sequences using range()
.
The range()
function gives you a sequence of numbers. You can use it with list comprehension to build lists quickly.
Example: Create numbers from 0 to 9
numbers = [x for x in range(10)]
print(numbers)
You can also create custom ranges, like only even numbers, by changing the range()
step value:
evens = [x for x in range(0, 11, 2)]
print(evens)
This is a simple way to make number patterns without writing long loops.
List Comprehension with Strings
List comprehension works great with strings too! Since strings are made of characters, you can loop through them just like a list.
Split Words into Characters
You can use list comprehension to turn a word into a list of its letters:
letters = [char for char in "hello"]
print(letters)
Change Case
You can use .upper()
or .lower()
in the expression to change letter cases:
upper_letters = [char.upper() for char in "hello"]
print(upper_letters)
Filter Vowels from a String
You can combine if
with list comprehension to pick only vowels:
vowels = [char for char in "beautiful" if char in "aeiou"]
print(vowels)
This is handy when working with user input or processing words.
Nested Loops in List Comprehension
List comprehension can include more than one for
loop. This is useful when you’re working with pairs of values or nested lists.
Simple 2D Loop Example (Multiplication Pairs)
You can use two loops to create all combinations between two lists:
pairs = [(x, y) for x in range(1, 4) for y in range(1, 4)]
print(pairs)
You can also use this to multiply each pair:
products = [x * y for x in range(1, 4) for y in range(1, 4)]
print(products)
Flattening a 2D List
If you have a list of lists (like a grid), you can flatten it into a single list using nested list comprehension:
matrix = [[1, 2], [3, 4], [5, 6]]
flat = [num for row in matrix for num in row]
print(flat)
This is a handy way to turn a table or grid into a simple list of values.
Using List Comprehension with Functions
You can call functions inside list comprehensions to transform each item. This works with built-in functions like .upper()
or even your own custom ones.
Using Built-in Functions
Here’s how to make all words in a list uppercase:
words = ["python", "is", "fun"]
upper_words = [word.upper() for word in words]
print(upper_words)
Using Custom Functions
You can also define your own function and use it in the comprehension:
def shout(word):
return word + "!"
excited = [shout(w) for w in ["hello", "world"]]
print(excited)
This makes it easy to apply any transformation to each item in a list.
List Comprehension with enumerate()
Sometimes, you may want to keep track of the index while using list comprehension. The enumerate()
function allows you to do this by adding index awareness.
Add Index Awareness
The enumerate()
function returns both the index and the value from the iterable. You can use this in a list comprehension to pair each element with its index.
For example, here’s how you can pair the index with the value in a list:
words = ["apple", "banana", "cherry"]
indexed_words = [(index, word) for index, word in enumerate(words)]
print(indexed_words)
Now each word is paired with its index in the list.
Example: Indexing with Custom Conditions
You can also apply a condition, while keeping track of the index:
words = ["apple", "banana", "cherry"]
even_indexed_words = [word for index, word in enumerate(words) if index % 2 == 0]
print(even_indexed_words)
In this case, only the words at even indices (0 and 2) are included.
List Comprehension with zip()
The zip()
function combines multiple iterables (like two lists) into pairs (or tuples), making it easy to work with related items in parallel. You can use zip()
with list comprehension to combine and process two or more lists simultaneously.
Combining Two Lists into Tuples
The zip()
function pairs up elements from two lists into tuples. Here’s an example where we combine first and last names into full names:
first_names = ["John", "Jane", "Alice"]
last_names = ["Doe", "Smith", "Johnson"]
full_names = [f"{first} {last}" for first, last in zip(first_names, last_names)]
print(full_names)
In this case, the two lists first_names
and last_names
are zipped together, and then the list comprehension formats them into full names.
Example: Pairing Items from Multiple Lists
You can also use zip()
to combine more than two lists. For example, if you have a list of ages and you want to create a list of sentences:
names = ["John", "Jane", "Alice"]
ages = [25, 30, 22]
sentences = [f"{name} is {age} years old." for name, age in zip(names, ages)]
print(sentences)
Dictionary & Set Comprehension
Just like list comprehension, Python also supports set comprehension and dictionary comprehension. While this article focuses on list comprehension, it’s helpful to know that similar syntax exists for sets and dictionaries as well.
Set Comprehension
Set comprehension works similarly to list comprehension but creates a set instead of a list, automatically removing duplicates.
unique_numbers = {x for x in range(1, 6)}
print(unique_numbers)
Dictionary Comprehension
You can also create dictionaries using comprehension. You define key-value pairs inside the comprehension.
squares_dict = {x: x * x for x in range(1, 6)}
print(squares_dict)
This is just a brief mention, but both sets and dictionaries have their own powerful use cases when combined with comprehension.
Conclusion
List comprehension is a powerful tool that helps you write cleaner, more efficient code. It allows you to loop through iterables, apply conditions, and transform data in a single line.
Practice using list comprehension in small tasks to get comfortable with it!