What's the difference between the list methods append() and extend()?
20 Answers
append adds an element to a list. extend concatenates the first list with another list/iterable.
>>> xs = ['A', 'B']
>>> xs
['A', 'B']
>>> xs.append("D")
>>> xs
['A', 'B', 'D']
>>> xs.append(["E", "F"])
>>> xs
['A', 'B', 'D', ['E', 'F']]
>>> xs.insert(2, "C")
>>> xs
['A', 'B', 'C', 'D', ['E', 'F']]
>>> xs.extend(["G", "H"])
>>> xs
['A', 'B', 'C', 'D', ['E', 'F'], 'G', 'H']
What is the difference between the list methods append and extend?
appendadds its argument as a single element to the end of a list. The length of the list itself will increase by one.extenditerates 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.