Difference between Append, Extend and Insert in Python
In Python, append(), extend() and insert() are list methods used to add elements to a list. Each method has different behaviors and is used in different scenarios.
Append
The append() method adds a single element which can be string, integer, tuple or another list to the end of the list. If we pass a list or another iterable, it will add the entire list as a single element.
Syntax:
list.append(element)
The element can be a string, integer, tuple or another list.
Example:
li = ['geeks']
# use method
li.append('for')
li.append('geeks')
# display list
print(l)
Insert
The insert() method allows us to insert an element(string, object or integer) at any specified position (index) in the list. If the index is greater than the list's length, the element is added to the end. If the index is negative, it starts counting from the end of the list.
Syntax:
list.insert(index, element)
Example:
li = ['geeks', 'geeks']
# use method
li.insert(1, 'for')
# display list
print(li)
Output:
['geeks', 'for', 'geeks']
Extend
The extend() method adds all the elements of an iterable (list, tuple, string) to the end of the list. Unlike append(), which adds a single element, extend() adds each element from the iterable to the list.
Syntax:
list.extend(iterable)
Example:
# python program to demonstrate
# working of extend function
# assign list
li = ['hello', 'welcome', 'to']
# use method
li.extend(['geeks', 'for', 'geeks'])
# display list
print(li)
Output:
['hello', 'welcome', 'to', 'geeks', 'for', 'geeks']
Difference between Append, Extend and Insert
Parameter | append() | insert() | extend() |
---|---|---|---|
Purpose | Adds a single element to the end of the list. | Inserts an element at a specified index in the list. | Adds each element from an iterable to the end of the list. |
Type of Argument | A single element (any data type, including a list). | An index (integer) and an element (any data type). | An iterable (list, tuple, string). |
Location of Insertion | Always at the end of the list. | At the specified index position in the list. | At the end of the list (each element from the iterable). |
Modifies the List | Yes, modifies the list in place. | Yes, modifies the list in place. | Yes, modifies the list in place. |
Multiple Items | No, only one element is added at a time. | No, only one element is added at a specified position. | Yes, it can add multiple items from the iterable. |
Iterables | It adds the list as a single element. | It can add a list, tuple, or any object at the specified index. | Adds elements from an iterable. |