Overview #
The list type is a container that holds a number of other objects, in a given order. The list type implements the sequence protocol, and also allows you to add and remove objects from the sequence.
Creating Lists #
To create a list, put a number of expressions in square brackets:
This construct is known as a “list display”. Python also supports computed lists, called “list comprehensions”. In its simplest form, a list comprehension has the following syntax:
where the expression is evaluated once, for every item in the sequence.
Accessing Lists #
Lists implement the standard sequence interface; len(L) returns the number of items in the list, L[i] returns the item at index i (the first item has index 0), and L[i:j] returns a new list, containing the objects between i and j.
If you pass in a negative index, Python adds the length of the list to the index. L[-1] can be used to access the last item in a list.
For normal indexing, if the resulting index is outside the list, Python raises anIndexError exception. Slices are treated as boundaries instead, and the result will simply contain all items between the boundaries.
Lists also support slice steps:
0 comments:
Post a Comment