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
student_list = ['Bob', 'Sally', 'Frank', 'Katie']
Let's add a single item to this list via append
student_list.append('Ted')
student_list
Awesome, that worked out well. Let's try to add multiple items to out student list via append
student_list.append(['Roger', 'Helen'])
student_list
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
student_list.pop()
student_list
student_list.extend(['Roger', 'Helen'])
student_list
Ahhh, there we go. Extend will take the individual items of your list, and add them as individual items to another list.
Check out more Python Vocabulary on our Glossary Page