Last modified: Oct 30, 2024 By Alexander Williams
Iterating Over a List and Adding to Another List in Python
Python offers several ways to iterate over a list and add items to a new list. This is useful for filtering, transforming, or extracting specific elements.
Using a for-Loop to Iterate and Add to a List
The for
-loop is one of the most common ways to iterate through a list in Python. Here’s a simple example:
original_list = [1, 2, 3, 4, 5]
new_list = []
for item in original_list:
new_list.append(item * 2)
print(new_list)
[2, 4, 6, 8, 10]
In this example, each element from original_list
is doubled and added to new_list
using append()
.
Using List Comprehension for Compact Code
List comprehensions are a powerful way to create new lists. They are often more concise than for
-loops.
original_list = [1, 2, 3, 4, 5]
new_list = [item * 2 for item in original_list]
print(new_list)
[2, 4, 6, 8, 10]
This one-line comprehension achieves the same result as the previous loop but with more readable code.
To learn more about looping and comprehensions, see Looping Through Lists to Create a Dictionary in Python.
Adding Elements Conditionally
Sometimes, you may want to add only certain elements. A conditional expression inside a list comprehension lets you filter items:
original_list = [1, 2, 3, 4, 5]
filtered_list = [item for item in original_list if item % 2 == 0]
print(filtered_list)
[2, 4]
In this example, only even numbers are added to filtered_list
.
Using extend() for List Concatenation
When adding multiple elements to a list, extend()
is more efficient than using append()
in a loop:
new_list = []
new_list.extend([item * 2 for item in original_list])
print(new_list)
[2, 4, 6, 8, 10]
Using extend()
adds all elements from the comprehension at once, improving performance with larger lists.
Conclusion
Python offers flexible ways to iterate and add items to a list. Choose from for
-loops, list comprehensions, or extend()
based on your needs for readability and efficiency.
For more techniques, explore Python’s documentation on list comprehensions.