91 views
Append vs Extend vs Insert in Python
The Python has append
, extend
, and insert
are methods used to add elements to lists, but they differ in how they add elements and where they add them in the list.
append()
Method:
- The
append()
method is used to add a single element to the end of a list. - It takes one argument, which is the element to be added.
- It modifies the original list in place.
my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # Output: [1, 2, 3, 4]
extend()
Method:
- The
extend()
method is used to add multiple elements (usually another list) to the end of a list. - It takes an iterable (e.g., a list, tuple, or string) as its argument.
- It unpacks the elements of the iterable and adds them one by one to the end of the original list.
- It also modifies the original list in place.
my_list = [1, 2, 3]
my_list.extend([4, 5, 6])
print(my_list) # Output: [1, 2, 3, 4, 5, 6]
insert()
Method:
- The
insert()
method is used to add an element at a specific index within the list. - It takes two arguments: the index at which to insert the element and the element itself.
- It modifies the original list in place.
my_list = [1, 2, 3]
my_list.insert(1, 4)
print(my_list) # Output: [1, 4, 2, 3]
In this example, 4
is inserted at index 1
, pushing the existing elements to the right.
Here’s a summary of their differences:
append()
adds a single element to the end.extend()
adds multiple elements to the end from an iterable.insert()
adds an element at a specific index.
Choose the method that best suits your specific use case and the desired location for adding elements to the list.