Sobes.tech
Junior

What is the difference between the append() and extend() methods in Python?

sobes.tech AI

Answer from AI

append() adds a single element to the end of the list. extend() adds all elements of an iterable object (list, tuple, string, etc.) to the end of the list.

# append()
list1 = [1, 2, 3]
list1.append(4)
# list1 now: [1, 2, 3, 4]

# extend()
list2 = [5, 6, 7]
list3 = [8, 9]
list2.extend(list3)
# list2 now: [5, 6, 7, 8, 9]

# append() vs extend() with an iterable object
list4 = [10, 11]
list4.append([12, 13])
# list4 now: [10, 11, [12, 13]]

list5 = [14, 15]
list5.extend([16, 17])
# list5 now: [14, 15, 16, 17]
Method Adds What it adds Example result when adding list [8, 9] to list [5, 6, 7]
append() One element The element itself (can be iterable) [5, 6, 7, [8, 9]]
extend() Multiple elements Elements of the iterable object [5, 6, 7, 8, 9]