Add Items to a List in Python
Here are the 4 most common ways to add items to a list in Python:
(1) Using append() method
The append()
method adds a single element to the end of the list.
For example:
my_list = [5, 10, 15]
# Add item to the end of the list
my_list.append(20)
print(my_list) # Output: [5, 10, 15, 20]
(2) Using insert() method
The insert()
method adds an element to the specified index within the list.
For example:
my_list = [5, 10, 15]
# Insert element at the beginning of the list
my_list.insert(0, 20)
print(my_list) # Output: [20, 5, 10, 15]
Indices in Python start at the position 0
. Therefore the first item is at the index 0
, the second item at the index 1
and so on.
(3) Using extend() method
The extend()
method adds all elements from an iterable (like another list or tuple) to the end of the list.
For example:
my_list = [5, 10, 15]
# Add elements from another list to the end of the list
my_list.extend([20, 25, 30])
print(my_list) # Output: [5, 10, 15, 20, 25, 30]
(4) Using + operator (concatenation)
The +
operator creates a new list by concatenating two or more lists.
my_list = [5, 10]
# Create a new list by concatenating two lists
new_list = my_list + [15, 20]
print(new_list) # Output: [5, 10, 15, 20]
The +
operator doesn’t modify the original list. It concatenates two lists to create a new list.
Choosing the right method
Use append()
to add a single element to the end of the list.
Use insert()
to insert an element at a specified position within the list.
Use extend()
to add multiple elements from an iterable (such as another list, or tuple) to the end of the list.
Use +
to combine multiple lists or keep the original list unchanged.