What is the difference between append() and extend() methods in Python?
Rashid D
rashid d profile pic

In Python, theappend() andextend() methods are used to add elements to a list, but they have distinct behaviors. Here's a detailed explanation of the differences between the two methods: 1. append() method: Theappend() method is used to add a single element to the end of a list. It modifies the original list by adding the specified element as a single item.

1
2
3
4
5
6

my_list = [1, 2, 3]

my_list.append(4)

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

In the example above, theappend(4) statement adds the element4 to the end of the listmy_list, resulting in[1, 2, 3, 4]. 2. extend() method: Theextend() 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 of the iterable to the original list.

1
2
3
4
5
6

my_list = [1, 2, 3]

my_list.extend([4, 5, 6])

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

In this example, theextend([4, 5, 6]) statement appends each element[4, 5, 6] individually to the end ofmy_list, resulting in[1, 2, 3, 4, 5, 6]. It's important to note that when usingextend(), the elements of the iterable are added individually to the list, whereasappend() adds the entire iterable as a single element.

1
2
3
4
5
6
7
8
9
10
11
12

my_list = [1, 2, 3]
another_list = [4, 5, 6]

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

my_list = [1, 2, 3]
another_list = [4, 5, 6]

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

As shown in the example,append() adds the entireanother_list as a single element, whereasextend() adds each element ofanother_list individually tomy_list. In summary,append() adds a single element to the end of a list, whileextend() adds multiple elements from an iterable to the end of a list. Choose the appropriate method based on your specific needs and the desired outcome.