e Learning

How to Append Multiple Items to List at Once in Python

In Python 3, the append() function adds a single item to an existing list. The append() method can only add one item at a time. If you want to add multiple elements at once, you’ll want to use the extend() method.

The syntax for the extend() method is given as follows:

list.extend([list])

The extend method takes a list of items as its argument and then adds each of its items to an existing list as a separate item.

The following code shows how the extend method works:

countries = ['Argentina', 'Bahamas', 'Canada']

print(countries)

countries.extend(['Denmark', 'Ireland', 'Luxembourg'])

print(countries)

In this example, we have a list called countries which contain three countries. Using the extend method, we added three new countries at once to the list.

python append multiple items to list
Extend Python List

Since the extend() function in Python accepts a list as its sole argument, we can pass another list to the extend function, as shown in the following example:

sequence1 = [1, 2, 3, 4]
sequence2 = [5, 6, 7, 8]

sequence1.extend(sequence2)

print(sequence1)

Note that the extend function adds each new item to the end of the list.