Introduction to Python Lists



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:
    L = []
    L = [expression, ...]
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:
    L = [expression for variable in sequence]
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.
    n = len(L)

    item = L[index]

    seq = L[start:stop]
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:
 seq = L[start:stop:step]

    seq = L[::2] # get every other item, starting with the first
    seq = L[1::2] # get every other item, starting with the second
The del statement can be used to remove an individual item, or to remove all items identified by a slice. The pop method removes an individual item and returns it, while remove searches for an item, and removes the first matching item from the list.
    del L[i]
    del L[i:j]


Share on Google Plus

About Vishnuprasad AS

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment