GNU Info

Info Node: (python2.1-tut.info)More on Lists

(python2.1-tut.info)More on Lists


Next: del statement Prev: Data Structures Up: Data Structures
Enter node , (file) or (file)node

More on Lists
=============

The list data type has some more methods.  Here are all of the methods
of list objects:

``append(x)''
     Add an item to the end of the list; equivalent to `a[len(a):] =
     [x]'.

``extend(L)''
     Extend the list by appending all the items in the given list;
     equivalent to `a[len(a):] = L'.

``insert(i, x)''
     Insert an item at a given position.  The first argument is the
     index of the element before which to insert, so `a.insert(0, x)'
     inserts at the front of the list, and `a.insert(len(a), x)' is
     equivalent to `a.append(x)'.

``remove(x)''
     Remove the first item from the list whose value is `x'.  It is an
     error if there is no such item.

``pop([i])''
     Remove the item at the given position in the list, and return it.
     If no index is specified, `a.pop()' returns the last item in the
     list.  The item is also removed from the list.

``index(x)''
     Return the index in the list of the first item whose value is `x'.
     It is an error if there is no such item.

``count(x)''
     Return the number of times `x' appears in the list.

``sort()''
     Sort the items of the list, in place.

``reverse()''
     Reverse the elements of the list, in place.

An example that uses most of the list methods:

     >>> a = [66.6, 333, 333, 1, 1234.5]
     >>> print a.count(333), a.count(66.6), a.count('x')
     2 1 0
     >>> a.insert(2, -1)
     >>> a.append(333)
     >>> a
     [66.6, 333, -1, 333, 1, 1234.5, 333]
     >>> a.index(333)
     1
     >>> a.remove(333)
     >>> a
     [66.6, -1, 333, 1, 1234.5, 333]
     >>> a.reverse()
     >>> a
     [333, 1234.5, 1, 333, -1, 66.6]
     >>> a.sort()
     >>> a
     [-1, 1, 66.6, 333, 333, 1234.5]

Using Lists as Stacks
Using Lists as Queues
Functional Programming Tools
List Comprehensions

automatically generated by info2www version 1.2.2.9