Add List Items
There are three methods to add items to a list: append()
, insert()
, and extend()
.
append():
This method appends items to the end of the existing list.
Example:
colors = ["voilet", "indigo", "blue"]
colors.append("green")
print(colors)
Output:
['voilet', 'indigo', 'blue', 'green']
What if you want to insert an item in the middle of the list? At a specific index?
insert():
This method inserts an item at the given index. The user has to specify the index and the item to be inserted within the insert()
method.
Example:
colors = ["voilet", "indigo", "blue"]
# [0] [1] [2]
colors.insert(1, "green") # inserts item at index 1
# updated list: colors = ["voilet", "green", "indigo", "blue"]
# indexes [0] [1] [2] [3]
print(colors)
Output:
['voilet', 'green', 'indigo', 'blue']
What if you want to append an entire list or any other collection (set, tuple, dictionary) to the existing list?
extend():
This method adds an entire list or any other collection datatype (set, tuple, dictionary) to the existing list.
Example 1:
# add a list to a list
colors = ["voilet", "indigo", "blue"]
rainbow = ["green", "yellow", "orange", "red"]
colors.extend(rainbow)
print(colors)
Output:
['voilet', 'indigo', 'blue', 'green', 'yellow', 'orange', 'red']
Example 2:
# add a tuple to a list
cars = ["Hyundai", "Tata", "Mahindra"]
cars2 = ("Mercedes", "Volkswagen", "BMW")
cars.extend(cars2)
print(cars)
Output:
['Hyundai', 'Tata', 'Mahindra', 'Mercedes', 'Volkswagen', 'BMW']
Example 3:
# add a set to a list
cars = ["Hyundai", "Tata", "Mahindra"]
cars2 = {"Mercedes", "Volkswagen", "BMW"}
cars.extend(cars2)
print(cars)
Output:
['Hyundai', 'Tata', 'Mahindra', 'Mercedes', 'BMW', 'Volkswagen']
Example 4:
# add a dictionary to a list
students = ["Sakshi", "Aaditya", "Ritika"]
students2 = {"Yash": 18, "Devika": 19, "Soham": 19} # only add keys, does not add values
students.extend(students2)
print(students)
Output:
['Sakshi', 'Aaditya', 'Ritika', 'Yash', 'Devika', 'Soham']
Concatenate two lists:
You can simply concatenate two lists to join them.
Example:
colors = ["voilet", "indigo", "blue", "green"]
colors2 = ["yellow", "orange", "red"]
print(colors + colors2)
Output:
['voilet', 'indigo', 'blue', 'green', 'yellow', 'orange', 'red']