Adding Elements in a List
You can add elements to an empty list or existing list using the methods append() and insert():
append()adds the element to the end of the list.insert()adds the element at the particular index of the list that you choose.- New element of one list can also be concatenated to the end of a second list object (requires two list objects)
1. Append() Method
The append() method is used to add a single element to the end of a list. It takes one argument, which is the element you want to add.
my_list = [1, 2, 3]
my_list.append(4)
print(my_list)
[1, 2, 3, 4]
2. Insert() Method
The insert() method is used to insert an element at a specified position in the list. It takes two arguments: the index at which to insert the element and the element itself.
my_list = [1, 2, 3]
my_list.insert(1, 4)
print(my_list)
[1, 4, 2, 3]