🐍 Python Q39 / 170

What is the difference between append() and extend()?

AI-Powered Answer ✓ Answered

In Python, both `append()` and `extend()` are list methods used to add elements to a list. While they both modify the list in-place by adding new items to its end, they differ significantly in how they handle their arguments and the type of arguments they expect.

append()

The append() method adds a single element to the end of a list. The element can be of any type, including another list, a tuple, a dictionary, or a simple data type. If you append an iterable (like another list), it will be added as a single item (a nested list) to the original list.

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

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

my_list.append('hello')
print(my_list)  # Output: [1, 2, 3, 4, [5, 6], 'hello']

extend()

The extend() method adds all the elements of an iterable (e.g., another list, tuple, string, or set) to the end of the current list. It essentially 'extends' the list by appending each item from the iterable individually. It expects an iterable as its argument.

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

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

my_list.extend('abc') # Adds characters 'a', 'b', 'c' individually
print(my_list)  # Output: [1, 2, 3, 4, 5, 6, 7, 'a', 'b', 'c']

Key Differences Summarized

Featureappend()extend()
Argument TypeTakes a single element (can be any object type).Takes an iterable (e.g., list, tuple, string, set).
How it AddsAdds the argument as a single item to the list. If the argument is an iterable, it's added as a nested object.Adds each item from the iterable argument individually to the list.
Resulting LengthIncreases the list length by 1.Increases the list length by the number of elements in the iterable argument.
Use CaseWhen you want to add one distinct item (even if that item is a collection itself) to the end of the list.When you want to merge an entire collection of items into the current list, effectively 'flattening' the addition.

In essence, append() is for adding one thing, while extend() is for adding many things from another collection. The choice between them depends on whether you want to add an object as a single item or merge its contents into the list.