DEV Community

Kevin Wojkovich
Kevin Wojkovich

Posted on

Python: To append or extend

I wrote a little tidbit this morning for my company, who is starting to roll out some Python-based services for the first time. We post little notes to help each other learn Python and to socialize the language in a shop that had only used Javascript previously.

I am up early looking at some boto3 examples and stumbled across the extend method on the Python List object. Previously I had only used the append method. Also this behavior changed slightly from version 2.X to 3.7, so perhaps that's where my confusion stemmed. (Check out the version differences in the Python docs link below.)

When working with lists in Python 3.7, it's pretty common to want to add more elements into that list. A common way to do this is would be to use the append method. This may not actually produce the structure you intend and using the extend method may be more intuitive.

Let's say you have two lists and use the append method:

a = [1,2,3]
b = ['z', 'y', 'x']

a.append(b)
print(a)
# [1,2,3,['z', 'y', 'x']]

The entire list b is appended to list a.
Let's use the extend method:

a = [1,2,3]
b = ['z', 'y', 'x']

a.extend(b)
print(a)
# [1,2,3,'x','y','z']

This adds each element of the iterable list b to the end of list a.
https://docs.python.org/3.7/tutorial/datastructures.html

Apparently it is also shorthand for an assignment of slices, which is kinda cool too.

Top comments (0)