Python: Add List item

In Python, we can use different method to add elements in list.

1. append():

Elements in python can be added by using append().In this process one element at a time can be added to the list by using append() method, for addition of multiple elements with the append() method, loops are used.

List=[]

List.append(3)
List.append(5)
List.append(9)

print(List)

Output: [3, 5, 9]

2. insert(): 

append() method can only be use  for addition of elements at the end of the List, for addition of element at the desired position, we use insert() method is used.

List = [1,2,3,4]
print("Before Insert: ", List)
List.insert(3, 15)
print("After Insert at position 3: ", List)
List.insert(1, 9)
print("After Insert at position 1: ", List)

Output

Before Insert:  [1, 2, 3, 4]
After Insert at position 3:  [1, 2, 3, 15, 4]
After Insert at position 1:  [1, 9, 2, 3, 15, 4]

3. extend():

We can use to add multiple value at the same time at the end of the list.

List = [1,2,3,4,5]
List.extend([6,7,8,9])
print(List)

Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]

Tags