Start learning free

LESSON 112 OF 673 · LISTS I

Insert and Remove at a Position in Python Lists

Lesson Read the full explanation

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

    PYTHON · LISTS I

    Array Insert Remove in Python, explained

    What insert and pop do

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

    insert(i, x) puts x at index i. Every item from index i on moves one place to the right, and the list gets one item longer. pop(i) takes out the item at index i. The items after it move one place to the left, and the list gets one item shorter.

    pets = ["Rex", "Milo", "Luna"]
    pets.insert(1, "Bella")
    print(pets)
    removed = pets.pop(2)
    print(removed, pets)
    
    ['Rex', 'Bella', 'Milo', 'Luna']
    Milo ['Rex', 'Bella', 'Luna']
    

    Both methods change the list in place. pop(i) also returns the item it removed, so keep it in a variable when you need it. insert returns None, so a line like pets = pets.insert(1, "Bella") would replace the list with None.

    Indexes move after a change

    After an insert or a removal, every item behind that spot has a new index. In the lesson, Milo starts at index 1. Once Bella is inserted at index 1, Milo moves to index 2. Removing him with pop(1) would take Bella out instead.

    Indexes past the end

    insert never fails because of a big index: it simply adds the item at the end. pop is stricter, and an index that doesn't exist raises an IndexError:

    a = ["a", "b"]
    a.insert(100, "z")
    print(a)
    a.pop(10)
    
    ['a', 'b', 'z']
    IndexError: pop index out of range
    

    Calling pop() on an empty list fails too, with the message pop from empty list.

    The lesson's task

    The list is ["Rex", "Milo", "Luna"]. Bella has an appointment and goes second, so pets.insert(1, "Bella") puts her at index 1, and Milo and Luna each move one place right. The next print(len(pets)) shows 4.

    Then Milo goes home. Since Bella came in, he is at index 2, so pets.pop(2) removes him. You don't need the value pop returns here. The last line prints the three pets left.

    pets = ["Rex", "Milo", "Luna"]
    pets.insert(1, "Bella")
    print(len(pets))
    pets.pop(2)
    print(pets[0], pets[1], pets[2])
    
    4
    Rex Bella Luna
    

    Other ways to remove and insert

    pop(i) removes by position. When you know the value but not the position, remove(value) deletes the first item equal to it, and later duplicates stay. del pets[0] also removes by position, but it returns nothing. A remove of a value that isn't there raises a ValueError.

    pets = ["Rex", "Milo", "Luna", "Milo"]
    pets.remove("Milo")
    print(pets)
    del pets[0]
    print(pets)
    pets.remove("Zed")
    
    ['Rex', 'Luna', 'Milo']
    ['Luna', 'Milo']
    ValueError: list.remove(x): x not in list
    

    Negative indexes work here as well. insert(-1, x) puts x before the last item, not after it. To add at the very end, use append, or insert(len(pets), x):

    p = ["a", "b", "c"]
    p.insert(-1, "X")
    print(p)
    
    ['a', 'b', 'X', 'c']
    

    Common mistakes

    • Doing the steps in the wrong order. The order decides which index holds which pet. Starting from ["Rex", "Milo", "Luna"], pop(1) then insert(1, "Bella") gives ['Rex', 'Bella', 'Luna']. Inserting first and then calling pop(1) removes Bella and gives ['Rex', 'Milo', 'Luna'].
    • Assigning the result of insert. After pets = pets.insert(1, "Bella"), printing pets shows None, because the method changes the list and returns nothing.
    • Counting the length too early. len(pets) reflects the list at the moment it is called. In the task the length is printed after the insert, so it is 4.

    Key takeaways

    • insert(i, x) adds x at index i and shifts the rest right.
    • pop(i) removes and returns the item at index i and shifts the rest left.
    • Work out indexes after earlier inserts and removals, not before.
    • insert accepts any index; pop raises IndexError for one that doesn't exist.
    Keep going with Python500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free