What’s the difference between the list methods append() and extend() in Python?

By | April 14, 2019

In this article we’ll explain the difference between two methods in Python: .append() and .extend()

Short explanation the difference between the list methods append() and extend() with examples:

append: Appends object at the end;

extend: Extends list by appending elements from the iterable.

Examples with append() and extend()

myList = [0, 1, 2]
myList.append([3, 4])
print (myList)

The result will be: [0, 1, 2, [3, 4]]
myList = [0, 1, 2]
myList.extend([3, 4])
print (myList)

The result will be: [0, 1, 2, 3, 4]

As you can see from above method .append() just adds an element to a list, and method .extend() concatenates the first list with a new list (or another iterable, not necessarily a list.)

Detailed explanation the difference between the list methods append() and extend():

  • append adds its argument as a single element to the end of a list. The length of the list itself will increase by one.
  • extend iterates over its argument adding each element to the list, extending the list. The length of the list will increase by however many elements were in the iterable argument.

Performance of append() and extend() methods in Python:

When we use these methods we don’t need to forget about their performance timing. If we need to append all elements in an iterable, use .extend() method. If you’re just adding one element, it’s much better to use .append() method. Below you can find timing performance append and extend methods to see on your own eyes:

Time performance append and extend methods with elements

>>> min(timeit.repeat(lambda: append([], abcdefghijklmnopqrstuvwxyz")))
2.867846965789795
>>> min(timeit.repeat(lambda: extend([], abcdefghijklmnopqrstuvwxyz")))
0.8060121536254883

Time performance append and extend methods with only one element

>>> min(timeit.repeat(lambda: append([], 0)))
0.2082819009956438
>>> min(timeit.repeat(lambda: extend([], 0)))
0.2397019260097295

Hope, this post helped you to understand the difference between extend and append methods in Python.

Leave a Reply

Your email address will not be published. Required fields are marked *