What is the difference between insert() and append() methods of a list?

Difference between insert() and append() methods of a list:

  • insert() method: It is used to insert an element at a specific position in the list. It takes two arguments: the index where the element should be inserted and the value of the element to be inserted. The elements following the specified index are shifted to the right to accommodate the new element.
my_list = [1, 2, 3, 4]
my_list.insert(2, 5)  # Inserts 5 at index 2
print(my_list)  # Output: [1, 2, 5, 3, 4]

 

  • append() method: It is used to add an element to the end of the list. It takes one argument, which is the value of the element to be appended.

Example:

my_list = [1, 2, 3, 4]
my_list.append(5)  # Appends 5 at the end
print(my_list)  # Output: [1, 2, 3, 4, 5]

In summary, insert() inserts an element at a specific position, whereas append() adds an element to the end of the list.

 

 


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *