Quick Earn Money

What's the difference between the list methods append() and extend()?

In Python, the append() and extend() methods are both used to modify lists, but they have different purposes and behaviors:

    append():
        The append() method is used to add an element to the end of a list.
        It takes a single argument, which is the element you want to add.
        The original list is modified in place, and the method does not return a new list.

    extend():
        The extend() method is used to add multiple elements to the end of a list.
        It takes an iterable (such as a list, tuple, or string) as an argument and appends each element from the iterable to the list.
        The original list is modified in place, and the method does not return a new list.

Here's an example to illustrate the differences:

python

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

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

In the append() example, the number 4 is added as a single element to the end of the list.

In the extend() example, the iterable [4, 5, 6] is added to the end of the list, so each individual element within the iterable becomes a new element in the list.

Choose between append() and extend() based on whether you want to add a single element or multiple elements to your list. If you're adding a single element, use append(). If you're adding multiple elements from an iterable, use extend().

Comments