Start learning free

LESSON 112 OF 673 · LISTS I

Insert and Remove at a Position in Python

Lesson

TL ; DR:

insert(i, x) puts x at index i. Use pop(i) to take out the item at index i. The other items move to make room or to close the gap.


colors = ["red", "green", "blue"]

colors.insert(1, "pink")
print(colors)   # ['red', 'pink', 'green', 'blue']

colors.pop(0)
print(colors)   # ['pink', 'green', 'blue']


Full lesson:

append adds an item at the end, and pop() takes the last one away. To work anywhere else in a list, give an index.

insert(i, x) puts x at index i. The items from index i on move one place to the right. The list gets one item longer.

pets = ["Rex", "Milo"]
pets.insert(0, "Luna")
print(pets)   # ['Luna', 'Rex', 'Milo']

pop(i) takes out the item at index i. The items after it move one place to the left. The list gets one item shorter.

pop(i) also returns the item it took out. Keep it in a variable when you need it:

first = pets.pop(0)
print(first)   # Luna
print(pets)    # ['Rex', 'Milo']

Watch the indexes. After an insert or a removal, the items behind that spot have new indexes.

insert never fails. An index past the end just adds the item at the end. But pop with an index past the end stops with an IndexError.


Your task

pets holds the pets waiting at the vet, in order.

Bella has an appointment, so she goes second, at index 1. Then Milo goes home. Take him out of the line.

The code below prints how many pets wait once Bella is in. At the end, it prints the pets left.

Expected output:

4
Rex Bella Luna
STEP 1 OF 2
    Ctrl + Enter to check