Building New Lists With Loops
In this tutorial, we'll create a new list from an existing sequence.
A common pattern is to start with one list and build another.
numbers = [1, 2, 3]
doubled = []
for number in numbers:
doubled.append(number * 2)
print(doubled)
Output:
[2, 4, 6]
The Pattern
The pattern has three steps:
1. Create an empty list 2. Loop over the original list 3. Append new values to the result list
Example:
names = ["ada", "grace", "linus"]
capitalized = []
for name in names:
capitalized.append(name.capitalize())
print(capitalized)
Filtering While Building
You can choose which items to include:
numbers = [-2, 5, 0, 8, -1]
positive_numbers = []
for number in numbers:
if number > 0:
positive_numbers.append(number)
print(positive_numbers)
Output:
[5, 8]
Transforming and Filtering Together
You can also change values before appending them:
words = ["ada", "", "grace"]
clean_names = []
for word in words:
if word != "":
clean_names.append(word.capitalize())
print(clean_names)
This skips empty strings and capitalizes the names that remain.
Common Mistake
Create the empty list before the loop, not inside it:
for number in numbers:
doubled = [] # wrong place
doubled.append(number * 2)
This resets the list every time.
Practice
Start with a list of words. Build a new list containing only words longer than five characters.