Add Items to Python List - Examples
Python - Add item(s) to List
To add one or more an items to a Python List, you can use append() method of list instance.
To add a single item to a list, call append() method on the list and pass the item as argument.
list.append(item)
If you would like to add items from an iterable to this list, use a For loop, and then add the items one by one to the list.
for item in iterable:
list.append(item)
In this tutorial, we shall learn how to use append() function to add one or mores items to a list in Python, with example programs.
1. Add an item "mango" to the given List in Python
In the following example program, we take a list with some initial values, and then add an item "mango" to the list using list append() method.
Python Program
my_list = ["apple", "banana", "cherry"]
my_list.append("mango")
print(my_list)
When you run this program, the new item "mango" is appended to my_list.
Output
['apple', 'banana', 'cherry', 'mango']
The new item is added to the end of given list.
2. Add multiple items to given List in Python
Suppose, we are given a list and an iterable. We have to add the items present in the iterable to the list.
We can use a For loop to iterate over the items in the iterable, and for each item, we can add the item to the list using list append() method.
In the following program, we are given a list my_list and an iterable iterable. We have to add the items present in iterable to the my_list using list append() method.
Python Program
my_list = ["apple", "banana", "cherry"]
iterable = ["mango", "fig", "pears"]
for item in iterable:
my_list.append(item)
print(my_list)
As there are no elements in the given list, append() function places the item in the list. First with 'Audi'
and then 'Volvo'
.
Output
['apple', 'banana', 'cherry', 'mango', 'fig', 'pears']
All the items present in the iterable are added to the given list my_list.
Summary
In this tutorial of Python Lists, we have seen how to add one or more items to a list, with the help of examples.