search

What is the difference between the "append" and "extend" methods in a Python list?

The append and extend methods are both used to add elements to a list in Python, but they work differently.

The **append** method adds an element to the end of a list as a single item. For example:

my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # Output: [1, 2, 3, 4]

The **extend** method, on the other hand, adds all the elements of a given iterable (such as a list or a tuple) to the end of the list. For example:

my_list = [1, 2, 3]
my_list.extend([4, 5, 6])
print(my_list) # Output: [1, 2, 3, 4, 5, 6]

In summary, **append** is used to add a single item to the end of a list, while **extend** is used to add all the elements of a given iterable to the end of the list.

Related Questions You Might Be Interested