What is the difference between append(), extend() and insert() on a list?
append(x) adds x as one item at the end. extend(iterable) adds each element of the iterable at the end. insert(i, x) puts x at position i and shifts later items right, which costs O(n).
Explain it simply
You have a bag of three mangoes. append drops a whole new basket into the bag as one item. extend empties the basket into the bag so every mango becomes its own item. insert pushes a mango into a chosen spot in the queue and makes everyone after it step back.
Example
a = [1, 2]
a.append([3, 4])
print(a) # Output: [1, 2, [3, 4]]
b = [1, 2]
b.extend([3, 4])
print(b) # Output: [1, 2, 3, 4]
c = [1, 2, 3]
c.insert(1, 99)
print(c) # Output: [1, 99, 2, 3]
d = [1]
d.extend("hi")
print(d) # Output: [1, 'h', 'i']All three change the list in place and return None.
What to say in the interview
"append adds a single object, even if it is a list; extend iterates over its argument and adds each element; insert places an item at an index and shifts the rest. append is amortised O(1), extend is O(k) for k new items, insert is O(n). All of them mutate and return None."
Common mistakes
- Writing
x = x.append(5). It setsxtoNone. - Using
extendwith a string and being surprised that it adds single characters.