Skip to content
Home » Append element in list Python

Append element in list Python

To append element in list Python has built-in methods for appending or adding elements to a list. We can also append one list to another.

1 . append(element)

This function adds the element at the end of the list.

lst = ["Chocolate", "Strawberry", "Pistachio", "Blue moon"]  
print('Current names List is:', lst)  
  
new_value = input("Please enter a name:\n")  
#append() method
lst.append(new_value)  
  
print('Updated name List is:', lst)  

Output:

Current names List is: [‘Chocolate’, ‘Strawberry’, ‘Pistachio’, ‘Blue moon’]
Please enter a name:
Butterscotch
Updated name List is: [‘Chocolate’, ‘Strawberry’, ‘Pistachio’, ‘Blue moon’, ‘Butterscotch’]

2. insert(index, element)

The insert() function inserts elements at the specified index point. It is useful when we need to insert an element at a specific location.

lst = [5, 10 , 15 , 20, 30, 35 , 40]  
print('Current Numbers List: ', lst)  

lst.insert(4, 25)  
print("The new list is: ",lst) 
 
num = int(input("enter a number to add to list:\n"))  
index = int(input('enter the index to add the number:\n'))  

#insert() method
lst.insert(index, num)  
print('Updated Numbers List:', lst)  

Output:

Current Numbers List: [5, 10, 15, 20, 30, 35, 40]
The new list is: [5, 10, 15, 20, 25, 30, 35, 40]
enter a number to add to list:
45
enter the index to add the number:
8
Updated Numbers List: [5, 10, 15, 20, 25, 30, 35, 40, 45]

3. extend(iterable)

The extends() function is used to add the iterable elements to the list. It accepts iterable object as an argument. 

lst = [15,20,35,40]  
#extend() method in list
lst.extend(["67.10", "75.92" ])
print(lst)  

#extending with tuples
lst.extend((80, 90))
print(lst)  

#extending with string
lst.extend("SimilarGeeks") 
print(lst)  

Output:

[15, 20, 35, 40, ‘67.10’, ‘75.92’]
[15, 20, 35, 40, ‘67.10’, ‘75.92’, 80, 90]
[15, 20, 35, 40, ‘67.10’, ‘75.92’, 80, 90, ‘S’, ‘i’, ‘m’, ‘i’, ‘l’, ‘a’, ‘r’, ‘G’, ‘e’, ‘e’, ‘k’, ‘s’]

Also Read:

Convert list to string in python

Tags: