Chapters
Python114 chapters

CollectionsChapter 27 of 114

Add Items

append, insert and extend, and the difference between them.

append adds one item to the end

Python
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:

Python
names = ["Ada"]
names = names.append("Grace")
print(names)

Output

None

insert puts one item at a position

Python
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:

Python
names = ["Ada"]
names.insert(99, "Grace")
print(names)

Output

['Ada', 'Grace']

extend adds many items

extend() takes an iterable and adds each item separately:

Python
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:

Python
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:

Python
letters = ["a"]
letters.extend("bc")
print(letters)

Output

['a', 'b', 'c']

Joining with +

+ builds a new list rather than changing either one:

Python
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:

Python
first = [1, 2]
first += [3]
print(first)

Output

[1, 2, 3]

Which to use

You wantUse
one more item at the endappend(x)
several more at the endextend(items)
an item at a positioninsert(i, x)
a new list from twoa + b

Test yourself

2 questions

What 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.

Next chapter

Remove Items

remove, pop, del and clear, and which one to reach for.