Python has various inbuilt functions which are helpful in day-to-day use case. In this article we will be focusing mainly on three functions namely 'append', 'extend' and 'insert' and how they are different from each other. These functions are mainly used on 'list' type of variables. Let's understand the difference with the help of below example.
Say, 'L' is a list type variable saving values 1,2,3,4,5. Now we want to add elements 8 & 9 in the same variable. We can achieve this task by any of the three functions. Here, we will use all three functions to understand their differences.
L = [1,2,3,4,5] #Variable declaration
L.append([8,9]) will update the 'L' variable as [1,2,3,4,5,[8,9]]
L.extend([8,9]) will update the 'L' variable as [1,2,3,4,5,8,9]
L.insert(5, [8,9]) will update the 'L' variable as [1,2,3,4,5,[8,9]]
Notice carefully, 'append' and 'insert' function have not unwrapped elements 8 & 9 from the list but 'extend' function did. This is one of the main difference between the three.
'Extend' function unwraps the elements inside the iterable and then adds them at last index value.
'Append' function works in similar manner except the unwrapping of the elements. It adds the elements as it is at the last index value.
'Insert' function provides more freedom when compared to the other two functions. It allows to decide the index position at which the element is to be added. We can add elements at any index as per our liking. Below are some examples of the same.
Insert function syntax is mentioned below:
Variable_name.insert(index value : Object)
L.insert(1, [8,9]) will update the 'L' variable as **[1, [8, 9], 2, 3, 4, 5]**
Here 1 is the index value where the elements[8,9] will be added.
L.insert(3, [8,9]) will update the 'L' variable as **[1, 2, 3, [8, 9], 4, 5]**
Here 3 is the index value where the elements[8,9] will be added.
Hope the above explanation is helpful to understand the difference between all the three functions. Share your thoughts in the comment section.