What is the difference between list methods append and extend

List append Method

append adds the object to the end of the list. The object could be any data type in Python, like list, dictionary or class object.

>>> A = [1, 2]
>>> A.append(3)
>>> A
[1, 2, 3]
>>> A.append([4, 5])
>>> A
[1, 2, 3, [4, 5]]

The length of the list will increase by one after the append is done.

List extend Method

extend extends the list by appending elements from the iterable argument. It iterates over the argument and then adds each element to the list. The given argument must be iterable type, like list, otherwise it will raise TypeError.

>>> A = [1, 2]
>>> A.extend(3)
Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    A.extend(3)
TypeError: 'int' object is not iterable

If you want to add 3 to the end of the list, you should firstly put the 3 in a new list.

>>> A = [1, 2]
>>> A.extend([3])
>>> A
[1, 2, 3]

extend method iterates the elements in the iterable object and then adds them one to one to the end of the list.

>>> A = [1, 2]
>>> A.extend([3, 4])
>>> A
[1, 2, 3, 4]

extend string type

Be aware that when the given object is a string type, it will append each character in the string to the list.

>>> A = ["a", "b"]
>>> A.extend("cde")
>>> A
['a', 'b', 'c', 'd', 'e']