Difference between append and extend in Python

Problem description

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

Problem sollution

The main difference between append() and extend() is that append() is used to add a single item to the end of a list, whereas extend() is used to add multiple items (from another iterable such as a list) to the end of a list, as shown in the examples below:

# example using append 

mylist =  ["apple", "banana", "cherry"]
new_element = "orange"

mylist.append(new_element)
print(mylist) # output: ["apple", "banana", "cherry", "orange"]
# example using extend 

mylist = ["apple", "banana", "cherry"]
new_elements = ["orange", "kiwi"]

mylist.extend(new_elements)
print(mylist) # output: ["apple", "banana", "cherry", "orange", "kiwi"]

But what if we swap the methods? Let's see:

# incorrect example using append 

mylist = ["apple", "banana", "cherry"]
new_elements = ["orange", "kiwi"]

mylist.append(new_elements)
print(mylist) # output: ["apple", "banana", "cherry", ["orange", "kiwi"]]

As you can see, Using append() in this example has caused the new_elements list to be treated as a single item.

# incorrect example using extend 

mylist =  ["apple", "banana", "cherry"]
new_element = "orange"

mylist.extend(new_element)
print(mylist) # output: ["apple", "banana", "cherry", "o", "r", "a", "n", "g", "e"]

In this case, using extend() has caused each character of the new_element string to be added individually to our list.

Summary

We should use append() when we want to add a single item to the end of a list, and extend() when we want to merge our list with another iterable, such as another list, by adding each of its elements individually to the end of the original list.