7.11: The insert() List Method

Making Games with Python and Pygame · LibreTexts

0%

Contents

    Text

    Size
    100%
    Theme
    Typeface
    Line length
    Spacing

    From LibreTexts, under CC BY-NC-SA 3.0, as the source states it; its equations are written in TeX, which the PDF shows typeset. This page at LibreTexts.

    7.11: The insert() List Method

    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]
    >>>
    

    This page titled 7.11: The insert() List Method was last modified on Wed, 06 Nov 2019 02:35:34 GMT and is shared under a CC BY-NC-SA 3.0 license and was authored, remixed, and/or curated by Al Sweigart via source content that was edited to the style and standards of the LibreTexts platform.