What's the difference between the list methods append() and extend() ?
What's the difference between the list methods append() and extend() ?
In Python, the list methods append() and extend() are used to add elements to a list, but they do so in different ways.
append()The append() method adds its argument as a single element to the end of a list, regardless of its type. This means that if the argument is a list, it will be added as a single nested list. For example:
my_list = [1, 2, 3]
my_list.append([4, 5])
print(my_list) # Output: [1, 2, 3, [4, 5]]
Here, [3][4] is added as a single element to my_list[1][2][3][4][5][6][7][8].
extend()The extend() method, on the other hand, takes an iterable (such as a list, tuple, set, or string) and appends each of its elements to the list, expanding the list. Each element of the iterable is added to the list individually:
my_list = [1, 2, 3]
my_list.extend([4, 5])
print(my_list) # Output: [1, 2, 3, 4, 5]
In this case, each element of [3][4] is added to my_list individually[1][2][3][4][5][6][7][8].
append() takes a single element; extend() takes an iterable.append() adds the argument as a singl...middle