Python - Append vs Extend List Methods

1 min read

The append() method is used for adding items to the end of a list. If you append a list to another list it will not unpack the values in the list being appended. For example:

a = [1, 2, 3]
b = [4, 5, 6]

a.append(b)
print(a)
# [1, 2, 3, [4, 5, 6]]

Note how the fourth item in the list above is a list of integers and not the number 4. The entire list b has been added as the fourth item to list a.

The extend() method unpacks the items from a list, tuple, set, string and so on into a list. For example:

a = [1, 2, 3]
b = [4, 5, 6]

a.extend(b)
print(a)
# [1, 2, 3, 4, 5, 6]

You can also use the += operator as shorthand to extend a list.

a = [1, 2, 3]
a += 'abc'

print(a)
# [1, 2, 3, a, b, c]


Author picture
Rhett Trickett

Founder at Able

@rhett RhettTrickett rhetttrickett
Python

Join the discussion

Able is a developer community where people build their coding knowledge and careers.

Join with GitHub Join with Twitter