Last modified: Oct 30, 2024 By Alexander Williams
Adding a List to Another List in Python
Combining lists is a common operation in Python. Here’s how to add one list to another using methods like extend()
and append()
.
Using extend() to Add a List
The extend()
method adds each element from one list to another. It’s the most efficient way to merge lists in Python.
list_a = [1, 2, 3]
list_b = [4, 5, 6]
list_a.extend(list_b)
print(list_a)
[1, 2, 3, 4, 5, 6]
In this example, extend()
combines list_b
into list_a
, making a single list.
Using + Operator to Concatenate Lists
The +
operator also joins lists by creating a new list without changing the original lists:
list_a = [1, 2, 3]
list_b = [4, 5, 6]
combined_list = list_a + list_b
print(combined_list)
[1, 2, 3, 4, 5, 6]
Using +
is straightforward but creates a new list, unlike extend()
which modifies the original list.
Using append() for Nested Lists
To add a list as a single element, use append()
. This creates a nested list structure:
list_a = [1, 2, 3]
list_b = [4, 5, 6]
list_a.append(list_b)
print(list_a)
[1, 2, 3, [4, 5, 6]]
Here, list_b
becomes an element inside list_a
. Use append()
if you need a nested list structure.
For more on appending lists, check Python Spread List Append: Adding Multiple Items Efficiently.
Using List Comprehension
List comprehension allows adding elements conditionally:
list_a = [1, 2, 3]
list_b = [item for item in [4, 5, 6] if item > 4]
list_a.extend(list_b)
print(list_a)
[1, 2, 3, 5, 6]
Only elements greater than 4 are added to list_a
. This approach provides flexibility in filtering items.
Conclusion
Python offers several ways to add lists together, each with unique benefits. Choose extend()
for modifying lists directly, +
for a new list, or append()
for nesting.
For more list operations, see Python's official documentation.