Skip to main content
Engineering LibreTexts

8.6: List Methods

[ "article:topic", "authorname:severancec", "python (language)", "license:ccbyncsa" ]
  • Page ID
    3137
  • Python provides methods that operate on lists. For example, append adds a new element to the end of a list:

     

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

    extend takes a list as an argument and appends all of the elements:

     

    >>> t1 = ['a', 'b', 'c']
    >>> t2 = ['d', 'e']
    >>> t1.extend(t2)
    >>> print(t1)
    ['a', 'b', 'c', 'd', 'e']

    This example leaves t2 unmodified.

    sort arranges the elements of the list from low to high:

     

    >>> t = ['d', 'c', 'e', 'b', 'a']
    >>> t.sort()
    >>> print(t)
    ['a', 'b', 'c', 'd', 'e']

    Most list methods are void; they modify the list and return None. If you accidentally write t = t.sort(), you will be disappointed with the result.