Appending items to a list in Python is an essential and common operation when working with different data structures. Sometimes, we need to add more than one item to a list at a time and in this article, we will explore the various ways to append multiple items to a list at the same time.
Using extend() Method
The extend() method is the most straightforward way to append multiple items to a list at once.
a = [1, 2, 3]
# Extend the list with multiple items
a.extend([4, 5, 6])
print(a)
Output
[1, 2, 3, 4, 5, 6]
extend() method takes an iterable(like a list, tuple, or set etc) and then adds each item from that particular iterable to the list.
Let's Explore some other methods to append multiple items to a list at once
Using + operator
Another way to add multiple items to a list is by simply using the '+' operator.
a = [1, 2, 3]
# Concatenate lists to add new items
a = a + [4, 5, 6]
print(a)
Output
[1, 2, 3, 4, 5, 6]
The '+' operator concatenates two lists, so we can create a new list with the items we want to add by simply adding the two lists.
Using List Comprehension
List Comprehension can be used to generate a new list and add items dynamically to that list.
a = [1, 2, 3]
# List comprehension to append multiple items
a += [x for x in range(4, 7)]
print(a)
We can use this method when we want to add elements based on a condition or when we want to transform the list before adding new items.
Using append() method in a loop
The append() method is used to add a single item to the end of a list, however to append multiple items at once using the append() method, we can use it in a loop. Here's how:
a = [1, 2, 3]
b = [4, 5, 6]
#Append multiple items one by one using a loop
for item in b:
a.append(item)
print(a)
Output
[1, 2, 3, 4, 5, 6]
Here we iterate over the items and call append() for each one, adding each element to the list one by one.