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 latter 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']

Please follow and like us:
This entry was posted in Python and tagged . Bookmark the permalink.

18 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).

    • Anonymous says:

      The method extend() and += operators are not identical. It has a subtle difference that you should concentrate on

      >>> a=[1,2,3]
      >>> a+=”hello”
      Traceback (most recent call last):
      File “”, line 1, in
      TypeError: can only concatenate list (not “str”) to list
      >>> a.extend(“hello”)
      >>> a
      [1, 2, 3, ‘h’, ‘e’, ‘l’, ‘l’, ‘o’]

  5. Akshay Bansal says:

    Thanks for the clarification

  6. jim says:

    Thanks a lot!

  7. Anonymous says:

    Minor typo: should be ‘former’/’latter’, not ‘former’/’later’

  8. Anonymous says:

    Nice, thanks!

  9. Anonymous says:

    Thank you very much!

  10. Jason says:

    Thank you, this was helpful. Something about the way you explained the difference between the two made it click for my brain!

  11. Anonymous says:


  12. Anonymous says:

    It’s really very helpful for me to understand this function

Leave a Reply

Your email address will not be published.