Python Extend – Add Items To List

Python extend will ‘extend’ a list of items to another list. It does this through individual items vs adding a list to the end of your list (like append).

Extend will iterate through your data, and add each piece one by one to your list.

list_of_students = ['Bob', 'Sally', 'Frank']
list_of_students.extend(['Roger', 'Katie'])

>> print (list_of_students)
['Bob', 'Sally', 'Frank', 'Roger', 'Katie']

If you just did append you’d actually be adding a list to the end of your list.

# Not what we want
list_of_students = ['Bob', 'Sally', 'Frank']
list_of_students.append(['Roger', 'Katie'])

>> print (list_of_students)
['Bob', 'Sally', 'Frank', ['Roger', 'Katie']]

If you can’t decide if you should use append or extend, try one and print out the items of your list. If it is not what you intend, use the other.

Let’s take a look at a python extend code sample

Python Extend

In Python, you'll often need to add more items to a list. You'll eventually add a list of items to another list.

This is where python extend comes into play. Let's look at extend and its close relative, append

In [5]:
student_list = ['Bob', 'Sally', 'Frank', 'Katie']

Let's add a single item to this list via append

In [6]:
['Bob', 'Sally', 'Frank', 'Katie', 'Ted']

Awesome, that worked out well. Let's try to add multiple items to out student list via append

In [7]:
student_list.append(['Roger', 'Helen'])
['Bob', 'Sally', 'Frank', 'Katie', 'Ted', ['Roger', 'Helen']]

Whoops, instead of adding multiple single items to our list, append added a single list of items at the end. This isn't what I wanted. I wanted Roger and Helen to be added as items just like the other students.

First we will drop the last item that didn't work, then lets try again via extend

In [8]:
['Bob', 'Sally', 'Frank', 'Katie', 'Ted']
In [9]:
student_list.extend(['Roger', 'Helen'])
['Bob', 'Sally', 'Frank', 'Katie', 'Ted', 'Roger', 'Helen']

Ahhh, there we go. Extend will take the individual items of your list, and add them as individual items to another list.

Link to code above

Check out more Python Vocabulary on our Glossary Page