Last modified: Jan 10, 2023 By Alexander Williams
How to Append Multiple Items to List in Python
In today's tutorial, we'll learn how to append multiple items to a list.
1. Using the append() method
The append() method adds a single element to an existing list.
To add multiple elements, we need:
1. iterate over the elements list.
2. append each element.
Let's see the example:
my_list = ["DJANGO"]
for i in ["PYTHON", "PHP"]:
my_list.append(i)
print(my_list)
So, in the above code, we try to append ["PYTHON", "PHP"] to my_list by:
1. iterate over ["PYTHON", "PHP"].
2. append element to my_list using the append() method.
output
['DJANGO', 'PYTHON', 'PHP']
2. Using '+' operator
Another way is using the '+' operator.
my_list = ["DJANGO"]
new_list = my_list + ["PYTHON", "PHP"]
#print
print(new_list)
output
['DJANGO', 'PYTHON', 'PHP']
3. Using extend() method
The extend() method adds list elements to the current list.
my_list = ["DJANGO"]
#append to the list
my_list.extend(["PYTHON", "PHP"])
#print
print(my_list)
output
['DJANGO', 'PYTHON', 'PHP']
Real example
Now, I'll give you an example in which we'll split a string into a list and append the list to an existing list.
#my list
my_list = ["DJANGO"]
#my string
my_string = "Hello PYTHON and PHP"
#Split the String
split_s = my_string.split(' ') #output ['Hello', 'PYTHON', 'and', 'PHP']
#append the result to my_list
my_list.extend(split_s)
print(my_list)
output
['DJANGO', 'Hello', 'PYTHON', 'and', 'PHP']