What's the difference between extend() and append()?

Both functions seem to add to the end of a list. However, when I use extend it seems to add each char to the list (below) rather than the entire string; which append does. What are the main differences between both functions and how would I use them? Please provide an example if possible. Thanks!

lst = [‘happy’, ‘heart’, ‘home’]
lst.extend(‘help’)
print(lst)

Output:
[‘happy’, ‘heart’, ‘home’, ‘h’, ‘e’, ‘l’, ‘p’]

you’re passing a string, ‘help’, not a list item. A string is an iterable.

.extend() adds all items of an iterable (list, string, tuple, etc).

you could do it this way,

lst = [‘happy’, ‘heart’, ‘home’]
lst.extend(['help'])

print(lst)

>>['happy', 'heart', 'home', 'help']

.append() adds an item to the end of a list.

lst = ['happy', 'heart', 'home']
>>> lst.append('help')
>>> print(lst)
['happy', 'heart', 'home', 'help']
>>> 

4 Likes

In addition to what @lisalisaj describes, we can use list.extend() to cheat a list from a string:

>>> a = []
>>> a.extend('abcdefghijklmnopqrstuvwxyz')
>>> a
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
>>> b = []
>>> b.extend(str(1234567890))
>>> b
['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']
>>> 

Nothing exciting or novel though, since it is the same as using the list() constructor.

2 Likes