Home »
Python »
Python programs
List append() and insert() methods in Python
Python list append() and insert() methods: Here, we are going to learn about the append() and insert() methods with example.
Submitted by Sanjeev, on April 06, 2019
Python list supports variety of built-ins functions in which append() and insert() are two functions
1) Python append() method
append() method is used to append values at the last position of the list that is every time you append a value it will directly go to the last of the list.
append() method takes only one argument.
Syntax:
list_name.append( any value )
Python insert() method
insert() method is also used to insert values in a list but the advantage of insert() method over append() method is that with the help of insert() method one can insert the values at any particular index (index should be less than the size of the list).
insert() method takes 2 argument one is index and other is value.
Syntax:
list_name.insert( index_value, any value )
Python code to demonstrate use, differences of append() and insert() methods
lst = [1, 2, 3, 4, 5, 6]
print('Original list:',*lst)
# appending two values in the
# existing list to show the
# working of append() function
lst.append(9)
lst.append(15)
print('\nList after appending 9 and 15')
print(*lst)
# inserting value 20 at index 2
lst.insert(2,20)
# inserting string literal 'include'
# at index 6
lst.insert(6,'include')
print('\nList after inserting 20 and "include"')
print(*lst)
print()
Output
Original list: 1 2 3 4 5 6
List after appending 9 and 15
1 2 3 4 5 6 9 15
List after inserting 20 and "include"
1 2 20 3 4 5 include 6 9 15
ADVERTISEMENT
ADVERTISEMENT