Add List Items

 

Add List Items

There are three methods to add items to 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. User has to specify 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"]
#       indexs              [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 = ["Maxon", "Sonu", "Kapil"]
students2 = {"Yash":18, "Vikas":19, "Krishna":19}    #only add keys, does not add values
students.extend(students2)
print(students)

Output:

['Maxon', 'Sonu', 'Kapil', 'Yash', 'Vikas', 'Krishna']

 

concatenate two lists:

you can simply concatenate two list to join two lists.

Example:

colors = ["voilet", "indigo", "blue", "green"]
colors2 = ["yellow", "orange", "red"]
print(colors + colors2)

Output:

['voilet', 'indigo', 'blue', 'green', 'yellow', 'orange', 'red']