Adding Elements in a List

You can add elements to an empty list or existing list using the methods append() and insert():

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]
Powered by Forestry.md