⬅ Previous Topic
Python Polymorphism – Same Thing, Different BehaviorNext Topic ⮕
Python Built-in Functions⬅ Previous Topic
Python Polymorphism – Same Thing, Different BehaviorNext Topic ⮕
Python Built-in FunctionsIn 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.
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.
Let’s first see how we normally make a new list from numbers 1 to 5:
numbers = []
for i in range(1, 6):
numbers.append(i)
print(numbers)
[1, 2, 3, 4, 5]
numbers = [i for i in range(1, 6)]
print(numbers)
[1, 2, 3, 4, 5]
i for i in range(1, 6)
means: “for every number i
from 1 to 5, take i
and put it into the list.”[ ]
mean we’re making a list.squares = [i*i for i in range(1, 6)]
print(squares)
[1, 4, 9, 16, 25]
Why? Because:
i = 1
→ 1*1 = 1
i = 2
→ 2*2 = 4
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 evenwords = ["apple", "banana", "cherry"]
uppercased = [word.upper() for word in words]
print(uppercased)
['APPLE', 'BANANA', 'CHERRY']
Why?
word.upper()
turns each word into uppercase.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”.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.
Try changing the numbers or words in the examples above and see what happens. The best way to learn is by playing around!
⬅ Previous Topic
Python Polymorphism – Same Thing, Different BehaviorNext Topic ⮕
Python Built-in FunctionsYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.