Adding Items to a List in Python: Using the Append Method
Learn how to add items to the end of a Python list using the append()
method. This guide provides a clear example of how to use the append()
function to extend your list and manage its contents efficiently.
Python - Add List Items
Append Items
To add an item to the end of the list, use the append()
method:
Example
Using the append()
method to add an item:
mylist = ["car", "bike", "boat"]
mylist.append("plane")
print(mylist)
Output
["car", "bike", "boat", "plane"]
Insert Items
To insert a list item at a specified index, use the insert()
method.
The insert()
method inserts an item at the specified index:
Example
Insert an item at the second position:
mylist = ["car", "bike", "boat"]
mylist.insert(1, "plane")
print(mylist)
Output
["car", "plane", "bike", "boat"]
Note: As a result of the examples above, the lists will now contain 4 items.
Extend List
To append elements from another list to the current list, use the extend()
method.
Example
Add the elements of additional_vehicles
to mylist
:
mylist = ["car", "bike", "boat"]
additional_vehicles = ["train", "plane", "helicopter"]
mylist.extend(additional_vehicles)
print(mylist)
Output
["car", "bike", "boat", "train", "plane", "helicopter"]
The elements will be added to the end of the list.
Add Any Iterable
The extend()
method does not have to append lists; you can add any iterable object (tuples, sets, dictionaries, etc.).
Example
Add elements of a tuple to a list:
mylist = ["car", "bike", "boat"]
mytuple = ("scooter", "skateboard")
mylist.extend(mytuple)
print(mylist)
Output
["car", "bike", "boat", "scooter", "skateboard"]