Saturday, March 8, 2014

Python Study Note: Data Structure - List

List is one of the most powerful structures in Python. It is defined as "a container that holds a number of other objects, in a given order". So it is quite general and extendable.

For List type, there are several aspects we need to know:

1. Generation
    1.1. Direct way
        a = []; b = [1,2,3]; c = ['today', 'is', 1, 'of', 'the', 0.5, 'day'];
        b = list(1,2,3);
    1.2. Sequence generation
         a = [x**2 for x in range(10)]
    1.3 Convert from other data structures
         a = (1,2,3); b = list(a)

2. Access
    2.1. Direct way
        a = range(10); b = a[1:5]
    2.2 Sequence way
        a = range(100); b = [1,2,3,10,40]; c = [a[i] for i in b];

3. Modification (list-level)
    3.1 list.append()        --- add item to the list
        a.append(10);
    3.2 list.extend()         --- add elements from list to the list
        a.extend([1,2,3]);
    3.3 list.insert(i, x)     --- add item to the list on specific location
        a.insert(len(a), 10) is equivalent to a.append(10)
    3.4 list.remove(x)     --- remove the first item from the list whose value is x, return error if there is no such item.
    3.5 list.pop([i])         --- Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list.
    3.6 list.index(x)        --- Return the index in the list of the first item whose value is x, return error if there is no such item
    3.7 list.count(x)        --- Return the number of times x appears in the list, return error if there is no such item
    3.8 list.sort() or list.sort(reverse = True) or list.reverse()  --- sort the list ...
    3.9 del statement       --- delete either any element (del(a[0])) or the whole list! (del a). Powerful, yet dangerous :)

4. Nested List
    If one generate a nested list as this:
        a = [[a,b] for a in range(10) for b in range(5)]
    To access to each individual:
        a[i][j]

Some additional useful functions on List:
1. How to merge two lists?
   c = a + b                  very straight forward, remember there is no a - b operation

NOTE: List is different from the matrix or vector as in Matlab, one can not directly run any mathematical operation on it, such as a = a + 1.

NOTE: two derived structures: Queue and Stack, how to do this? following examples:
1. Queue
    a = range(10); a.append('new-entry'); a.pop(0);
2. Stack
    a = range(10); a.append('new-entry'); a.pop();

No comments:

Post a Comment