What is the difference between Python's list methods append and extend?
The append
method adds an item to the end of a list. The item can be of any type (integer, string, etc.).
The extend
method adds all the items in an iterable (such as a list) to the end of the list.
Here's an example:
fruits = ['apple', 'banana', 'mango']
# Append an item to the list
fruits.append('orange')
print(fruits) # ['apple', 'banana', 'mango', 'orange']
# Extend the list with another list
fruits.extend(['strawberry', 'kiwi'])
print(fruits) # ['apple', 'banana', 'mango', 'orange', 'strawberry', 'kiwi']
The main difference between the two is that append
adds a single item to the list, while extend
adds all the items in an iterable to the list.