In Python, both append() and extend() are methods that can be used to add elements to a list. However, there is a key difference between the two methods.
The append() method is used to add a single element to the end of the list. The element can be of any data type, including another list. When you call the append() method with an argument, it is added as a single element to the end of the list.
For example, consider the following code:
my_list = [1, 2, 3]
my_list.append(4)
print(my_list)
[1, 2, 3, 4]
The output of this code will be [1, 2, 3, 4].
On the other hand, the extend() method is used to add multiple elements to the end of the list. The elements can be provided as a list or any other iterable data type. When you call the extend() method with an argument, it is added as individual elements to the end of the list.
For example, consider the following code:
my_list = [1, 2, 3]
my_list.extend([4, 5, 6])
print(my_list)
[1, 2, 3, 4, 5, 6]
The output of this code will be [1, 2, 3, 4, 5, 6].
To summarize, the append() method adds a single element to the end of a list, while the extend() method adds multiple elements to the end of a list by taking an iterable as input.
Comments
Post a Comment