Saturday, July 2, 2011

How to work with Python Lists - Beginers Guide

Consider list as numbered containers
which can hold different data and objects


It keeps objects in an order like an array, accessible like list[n].
A list is a sequencial data structure which allows you to add and remove objects from
the sequencial list.

How to create Lists
    L = [] # creates an empty list
    L = [1,2,3] # list with Numbers
    L = ["A","B","C"] # list with Strings
    L = ["a:A","b:B","d:C"] # list with Key pairs
    L1 = [1,"A",L] # list with mixed data
    L = [a, b, c]# list with objects

           which may have a.move() like processes
    L = [expression, ...]


You can put all kinds of objects in lists, including other lists, and multiple references to a
single object.

A = B = [] # both names points to the same list

>>> A=B=[]
>>> A=[1,2,3]
>>> B
[]
>>> A=B=[1,2,3]
>>> A.pop()
3
>>> A
[1, 2]
>>> B
[1, 2]
>>>


A = []
B = A # both names will point to the same list

A = []; B = [] # two independent lists


How to Acces Lists

len(L) # returns the number of items
the first item is L[0]

L[i:j] # creates a new list with objects between i and j.
    n = len(L)
    item = L[index]
    sequence = L[start:stop]


L[-1]  # access the last item in a list.
How to do Lists slicing
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

>>> A
[1, 2, 3]
>>> A[0:2]
[1, 2]
>>> A[0:2:2]
[1]
>>> A[0:2:1]
[1, 2]
>>>
>>> A[0:4:1]
[1, 2, 3]
>>>


How to Loop over Lists
How to use for-in statement
    for item in L:
        print item

How to use enumerate function with lists
    for index, item in enumerate(L):
        print index, item

How to use range and len with lists
    for index in range(len(L)):
        print index


>>> for a in A:
 print a
1
2
3

How to use explicit iterator
    i = iter(L)
    item = i.next() # fetch first value
    item = i.next() # fetch second value

>>> i=iter(A)
>>> i.next()
1
>>> i.next()
2
>>>


How to sum list containing numbers
    v = sum(L)
    total = sum(L, subtotal)
    average = float(sum(L)) / len(L)

>>> sum(A)
6


How to add individual items and slices
    L[i] = get one obj
    L[i:j] = slice sequence of items


How to auto update list values
    L = []
    M = L

    # modify both lists M & L
    L.append(obj)


>>> A.append(4)
>>> A
[1, 2, 3, 4]
>>> B
[1, 2, 3, 4]
>>>

How to create news lists
    L = [] # empty
    M = L[:] # create a copy

    # modify L only
    L.append(obj)


>>> M=A[:]
>>> M
[1, 2, 3, 4]
>>> B
[1, 2, 3, 4]
>>> M.append(5)
>>> M
[1, 2, 3, 4, 5]
>>> A
[1, 2, 3, 4]
>>>

How to insert an items to a list.
    L.append(item)# adds to the end
    L.insert(index, item)# inserts an item at a given index, moves rest down


>>> M.insert(0, 0)
>>> M
[0, 1, 2, 3, 4, 5]



How to delete items in a list    del L[i]
    del L[i:j]

>>> del M[0]
>>> M
[1, 2, 3, 4, 5]

>>> del M[0:1]
>>> M
[2, 3, 4, 5]
>>>


pop method removes an individual item and returns it,
remove searches and removes the first matching item.

    item = L.pop() # last item
    item = L.pop(0) # first item
    item = L.pop(index)
    L.remove(item)

>>> M.pop()
5
>>> M
[2, 3, 4]

The del and pop defference is pop returns the removed item.

How to reverse a list.
    L.reverse()
>>> M.reverse()
>>> M
[4, 3, 2]
>>>


Inserting/and deleting items on the top is fast if you use reverse
    L.reverse()
    # append/insert/pop/delete at far end
    L.reverse()


>>> M.append(1)
>>> M.reverse()
>>> M
[1, 2, 3, 4]
>>>


How sort lists and get a sorted copy
    L.sort() # sort L, L changed
   out = sorted(L) # returns a sorted copy L not changed


>>> M
[1, 2, 3, 4]
>>> M.insert(2,5)
>>> M
[1, 2, 5, 3, 4]
>>> M
[1, 2, 5, 3, 4]
>>> M.sort()
>>> M
[1, 2, 3, 4, 5]
>>>


How to get the smallest or largest item
    lo = min(L)
    hi = max(L)


>>> max(M)
5
>>> min(M)
1
>>>


Be careful when deleting in a loop
for object in L[:]:
    if not condition:
            del L[index]
this can create problem as for keeps an internal index
create a new list and append items
out = []
for object in L:
     if condition:
         out.append(object)
finally remove L

How to implement stack data structure with lists
    stack = []
    stack.append(object) # push
    object = stack.pop() # pop from end

How to implement queue data structure with lists
    queue = []
    queue.append(object) # push
    object = queue.pop(0) # pop from beginning


How to search in lists
    if value in L:
        print "list contains", value


How get the index of the first matching item
    i = L.index(value)

To get all matching items, use a loop, passing a start index:

    def findall(L, value, start=0):
        # generator version
        i = start - 1
        try:
            i = L.index(value, i+1)
            yield i
        except ValueError:
            pass

    for index in findall(L, value):
        print "match at", i


If you need to count matching items
    n = L.count(value)

No comments:

Post a Comment