









Python List Comprehension
Create Lists
In Python, there's a short and neat way to create new lists. It’s called list comprehension. It looks a little different from what you've seen before, but don't worry — you'll understand it step by step.
What is List Comprehension?
List comprehension is a way to create a new list by doing something to each item in another list (or a range of numbers).
Instead of writing a loop and appending to a list, you can write it all in one line.
Normal Way vs List Comprehension
Let’s first see how we normally make a new list from numbers 1 to 5:
Using a for loop:
numbers = []
for i in range(1, 6):
numbers.append(i)
print(numbers)
[1, 2, 3, 4, 5]
Now, using list comprehension:
numbers = [i for i in range(1, 6)]
print(numbers)
[1, 2, 3, 4, 5]
Explanation:
i for i in range(1, 6)
means: “for every numberi
from 1 to 5, takei
and put it into the list.”- The square brackets
[ ]
mean we’re making a list.
Example 2: Square Each Number
squares = [i*i for i in range(1, 6)]
print(squares)
[1, 4, 9, 16, 25]
Why? Because:
- When
i = 1
→1*1 = 1
- When
i = 2
→2*2 = 4
- ... and so on
Example 3: Double Only Even Numbers
doubles = [i*2 for i in range(1, 6) if i % 2 == 0]
print(doubles)
[4, 8]
Why?
i % 2 == 0
checks if a number is even- Only 2 and 4 are even between 1 to 5
- So we double only those: 2→4, 4→8
Example 4: Convert to Uppercase
words = ["apple", "banana", "cherry"]
uppercased = [word.upper() for word in words]
print(uppercased)
['APPLE', 'BANANA', 'CHERRY']
Why?
word.upper()
turns each word into uppercase.- Each word from the list is transformed and put into a new list.
Example 5: Filter Words Starting with "b"
words = ["apple", "banana", "cherry", "blueberry"]
starts_with_b = [word for word in words if word.startswith("b")]
print(starts_with_b)
['banana', 'blueberry']
Why?
word.startswith("b")
checks if the word starts with the letter “b”.- Only “banana” and “blueberry” match that rule.
Summary
List comprehension is just a shortcut to make lists. It’s clean and easy once you practice a few times.
Here's the basic pattern to remember:
[expression for item in collection if condition]
You can skip the if
part if you don’t need to filter anything.