Monday, July 25, 2011

Quick Guide to Python List Operations

mylist=[]
x=20

mylist.append(x)
# Add an item to the end of the list;

mylist.insert(i, x) 
# insert at i , i should exsit

list.exytend(L) 
# Extend the list by appending all the items in the given list

mylist.insert(len(a), x) is equivalent to a.append(x).

mylist.remove(x)
Remove the first item from the list whose value is x.

mylist.pop([i])
Remove the item at the given position in the list, and return it.

Mylist.pop()
# removes and returns the last item in the list.

mylist.index(x)
# Return the index in the list of the first item whose value is x.

mylist.sort() 
# Sort the items of the list, in place.

mylist.reverse()
# Reverse the elements of the list, in place.


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

============ADVANCED ==============





Using Lists as Stacks

The list methods make it very easy to use a list as a stack, where the last element added is the first element retrieved (“last-in, first-out”). To add an item to the top of the stack, use append(). To retrieve an item from the top of the stack, use pop() without an explicit index. For example:

>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack
[3, 4]

Using Lists as Queues

It is also possible to use a list as a queue, where the first element added is the first element retrieved (“first-in, first-out”); however, lists are not efficient for this purpose. While appends and pops from the end of list are fast, doing inserts or pops from the beginning of a list is slow (because all of the other elements have to be shifted by one).

No comments:

Post a Comment