Python list: difference between append and extend

When manipulating lists, you have access to two methods called append() and extend(). The former appends an object to the end of the list (e.g., another list) while the later appends each element of the iterable object (e.g., another list) to the end of the list.

For example, we can append an object (here the character ‘c’) to the end of a simple list as follows

>>> stack = ['a','b']
>>> stack.append('c')
>>> stack
['a', 'b', 'c']

If we append a list made of several items, the result as expected is (a list is an object):

>>> stack.append(['e','f'])
>>> stack
['a', 'b', 'c', ['e', 'f']]

However, sometimes what we want is to append all the elements contained in the list rather the list itself. You can do that manually of course, but a better solution is to use extend() as follows:

>>> stack.extend(['g','h'])
>>> stack
['a', 'b', 'c', ['e', 'f'], 'g', 'h']

This entry was posted in Python and tagged . Bookmark the permalink.

9 Responses to Python list: difference between append and extend

  1. Anonymous says:

    can you change the title from expand to append? thanks

  2. Anonymous says:


  3. Anonymous says:

    Minor typo. anothre should be another. Nice post!

  4. Anonymous says:

    so it’s like:
    >>> lst1 = [‘a’, ‘b’, ‘c’]
    >>> lst2 = [‘d’, ‘e’]
    >>> lst1 += lst2
    >>> lst1
    [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]

    did i understand it right?

    • the += operator behaves like the extend() method indeed. Note that the += should be slightly faster (because the .extend() method involves a function call). However, the extend() method can be used in context where the += operator cannot (for instance you can chain function calls).

  5. Akshay Bansal says:

    Thanks for the clarification

  6. jim says:

    Thanks a lot!

Leave a Reply

Your email address will not be published.