Last modified: Sep 07, 2023 By Alexander Williams
How to Append Multiple Items to List in Python
Today, we'll look at 4 easy methods to add items to a Python list. If you're ready, let's get started!
1. Using the append() method
We can use the append() function in a loop to append multiple items to a list. let's see an example:
my_list = [1, 2, 3]
new_items = [4, 5, 6]
# Append multiple items using a loop
for item in new_items:
my_list.append(item)
print(my_list)
Output:
[1, 2, 3, 4, 5, 6]
Let me explain the code:
-
Define list called
my_list
containing the initial items [1, 2, 3]. -
Define a new list called new_items with the items to add to my_list.
-
Use a for loop to iterate through each item in the
new_items
list. -
Append each item to my_list using append() inside the loop.
2. Using the extend() Method
We can also use the extend()
function to append multiple items to a list.
This function takes an iterable (such as a list or tuple) as an argument and appends each item from the iterable to the list.
Here's an example:
my_list = [1, 2, 3]
new_items = [4, 5, 6]
# Append multiple items using extend()
my_list.extend(new_items)
print(my_list)
Output:
[1, 2, 3, 4, 5, 6]
3. Using List Concatenation Method
With the list concatenation method, you can concatenate two lists, such as:
my_list = [1, 2, 3]
new_items = [4, 5, 6]
# Append multiple items using list concatenation
my_list = my_list + new_items
print(my_list)
Output:
[1, 2, 3, 4, 5, 6]
As you can see, we've concatenated my_list
with new_items
using the +
operator.
4. Using List Comprehension method
List Comprehension is the last method in this tutorial for appending multiple items to a list. This method is like the append()
method in a loop, but it uses an inline loop instead.
my_list = [1, 2, 3]
new_items = [4, 5, 6]
# Append multiple items using list comprehension
my_list += [item for item in new_items]
print(my_list)
Conclusion
Now that you know 4 methods to add more than one item to a list, you can decide which one you like best.
if you want to learn how to append to a list using a while loop, visit Methods to Append to String in a Loop in Python.