Python List

The first thing to do today is to learn “Python List”. Reference links are here and here

Here are a few things to note:
1. python list need not to be of the same type
2. list indices start from “0”
3. slice example:
a= [1,2,3,4,5]

a[1:-1] – slice the list from index 1 but stops at the item before -1
>>>a
>>>[2,3,4]

4. items can be added, changed, and removed
5. to get the length of the list – len(list)
6. nest list is to create list in a list

b=[‘p’,’q’]
a=[1,2,b]
>>>a
>>>[1,2, [‘p’, ‘q’]]

7. difference between list.append and list.extend

x=[1,2,3]
x.append([4,5])
>>>x
>>>[1,2,3,[4,5]]

y=[1,2,3]
y.extend([4,5])
>>>y
>>>[1,2,3,4,5]

8. list.insert(i,x) – insert x at position i; original item at position i will be pushed backward
9. list.remove(x) – only removes the first item that match x.
10. list.pop([i]) – [] means “i” is optional. if without “i”, it will pop the last item in the list.
11. list.index(x) – returns the index of the first appearance of x
12. list.count(x) – return the number of times x appear
13. list.sort() – sort the list in ascending order
14. list.reverse() – reverse the order of the list
15. can be used as stack – append and pop – last in first out
16. can be used as queue – first in first out – use collections.deque (from collections import deque) – popleft() will remove the first one to arrive – append will add at the back of the list.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s