CollectionsChapter 27 of 114
Add Items
append, insert and extend, and the difference between them.
append adds one item to the end
names = ["Ada"]
names.append("Grace")
names.append("Katherine")
print(names)Output
['Ada', 'Grace', 'Katherine']
append() changes the list and returns None. That is deliberate — it is a reminder that the work happened in place — and it produces a classic bug:
names = ["Ada"]
names = names.append("Grace")
print(names)Output
None
insert puts one item at a position
names = ["Ada", "Katherine"]
names.insert(1, "Grace")
print(names)Output
['Ada', 'Grace', 'Katherine']
The item lands at that index, pushing the rest along. An index past the end does not fail; it simply appends:
names = ["Ada"]
names.insert(99, "Grace")
print(names)Output
['Ada', 'Grace']
extend adds many items
extend() takes an iterable and adds each item separately:
names = ["Ada"]
names.extend(["Grace", "Katherine"])
print(names)Output
['Ada', 'Grace', 'Katherine']
Compare it with append(), which adds whatever you give it as a single item:
names = ["Ada"]
names.append(["Grace", "Katherine"])
print(names)
print(len(names))Output
['Ada', ['Grace', 'Katherine']] 2
The list now holds two items, and the second one is itself a list. That is sometimes what you want and usually not.
extend takes any iterable
Including a string, which is a sequence of characters — another surprise worth meeting on purpose:
letters = ["a"]
letters.extend("bc")
print(letters)Output
['a', 'b', 'c']
Joining with +
+ builds a new list rather than changing either one:
first = [1, 2]
second = [3, 4]
both = first + second
print(both)
print(first)Output
[1, 2, 3, 4] [1, 2]
+= on a list behaves like extend(), changing it in place:
first = [1, 2]
first += [3]
print(first)Output
[1, 2, 3]
Which to use
| You want | Use |
|---|---|
| one more item at the end | append(x) |
| several more at the end | extend(items) |
| an item at a position | insert(i, x) |
| a new list from two | a + b |
Test yourself
2 questionsWhat does names.append(["a", "b"]) add to the list?
Show the answer
One item, which is a list — append adds whatever you give it as a single item. extend adds each item separately.
What is names after names = names.append("Grace")?
Show the answer
None — append changes the list in place and returns None, so assigning the result throws the list away.
Remove Items
remove, pop, del and clear, and which one to reach for.