Difference between Append, Extend and Insert in Python

In Python, append, extend, and insert are all methods used to add elements to a list. However, they differ in how they add elements to the list.

  • append: append is a method that adds an element to the end of the list. For example:
list1 = [1, 2, 3]
list1.append(4)
print(list1)  # Output: [1, 2, 3, 4]

extend: extend is a method that takes an iterable (e.g., list, tuple, string) as an argument and adds each element of the iterable to the end of the list. For example:

list1 = [1, 2, 3]
list1.extend([4, 5])
print(list1)  # Output: [1, 2, 3, 4, 5]

insert: insert is a method that takes two arguments: an index at which to insert the element and the element to be inserted. For example:

list1 = [1, 2, 3]
list1.insert(1, 4)
print(list1)  # Output: [1, 4, 2, 3]

Note that append and extend add elements to the end of the list, whereas insert can add an element at any position in the list.

Conclusion:

In conclusion, append(), insert(), and extend() are all methods in Python used to add elements to a list, but they differ in how they add the elements. append() adds an element to the end of the list, insert() adds an element at a specific position, and extend() adds elements from an iterable to the end of the list. Depending on your use case, you can choose the appropriate method to add elements to your list.