Both append() and extend() are methods of a list in Python, used to add elements to a list.
The append() method adds a single element to the end of the list, while the extend() method adds multiple elements to the end of the list by appending each element one by one.
Here is an example to demonstrate the difference between the two methods:
my_list = [1, 2, 3] # Using append() my_list.append([4, 5, 6]) print(my_list) # Output: [1, 2, 3, [4, 5, 6]] # Using extend() my_list = [1, 2, 3] my_list.extend([4, 5, 6]) print(my_list) # Output: [1, 2, 3, 4, 5, 6]
As shown in the example, append() adds the entire list [4, 5, 6] as a single element at the end of the list, while extend() adds each element of the list [4, 5, 6] one by one to the end of the list.
Therefore, if you want to add multiple elements to a list, you should use the extend() method. If you want to add a single element to a list, you should use the append() method.
0 Comments