8.7: Deleting Elements

Python for Everybody · LibreTexts

0%

Contents

    Text

    Size
    100%
    Theme
    Typeface
    Line length
    Spacing

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

    8.7: Deleting Elements

    There are several ways to delete elements from a list. If you know the index of the element you want, you can use pop:

    >>> t = ['a', 'b', 'c']
    >>> x = t.pop(1)
    >>> print(t)
    ['a', 'c']
    >>> print(x)
    b

    pop modifies the list and returns the element that was removed. If you don't provide an index, it deletes and returns the last element.

    If you don't need the removed value, you can use the del operator:

    >>> t = ['a', 'b', 'c']
    >>> del t[1]
    >>> print(t)
    ['a', 'c']

    If you know the element you want to remove (but not the index), you can use remove:

    >>> t = ['a', 'b', 'c']
    >>> t.remove('b')
    >>> print(t)
    ['a', 'c']

    The return value from remove is None.

    To remove more than one element, you can use del with a slice index:

    >>> t = ['a', 'b', 'c', 'd', 'e', 'f']
    >>> del t[1:5]
    >>> print(t)
    ['a', 'f']

    As usual, the slice selects all the elements up to, but not including, the second index.


    This page titled 8.7: Deleting Elements was last modified on Tue, 01 Dec 2020 03:50:56 GMT and is shared under a CC BY-NC-SA 4.0 license and was authored, remixed, and/or curated by Chuck Severance via source content that was edited to the style and standards of the LibreTexts platform.