Skip to main content
Engineering LibreTexts

7.11: The insert() List Method

  • Page ID
  • Unlike the append() list method that can only add items to the end of a list, the insert() list method can add items anywhere inside the list. The first parameter for insert() is the index where the item should go (all the items originally at this index and after have their indexes increase by one). If the argument passed for the first parameter is larger than the length of the list, the item is simply added to the end of the list (just like what append() does). The second parameter for insert() is the item value to be added. Type the following into the interactive shell to see how insert() works:

    >>> spam = ['cat', 'dog', 'bat']
    >>> spam.insert(0, 'frog')
    >>> spam
    ['frog', 'cat', 'dog', 'bat']
    >>> spam.insert(10, 42)
    >>> spam
    ['frog', 'cat', 'dog', 'bat', 42]
    >>> spam.insert(2, 'horse')
    >>> spam
    ['frog', 'cat', 'horse', 'dog', 'bat', 42]