What’s the difference between the list methods append() and extend()?

Technology CommunityCategory: PythonWhat’s the difference between the list methods append() and extend()?
VietMX Staff asked 3 years ago

append adds an element to a list, and extend concatenates the first list with another list (or another iterable, not necessarily a list).

Consider:

x = [1, 2, 3]
x.append([4, 5])
print (x)
# [1, 2, 3, [4, 5]]

x = [1, 2, 3]
x.extend([4, 5])
print (x)
# [1, 2, 3, 4, 5]