List

Built-in functions

In [ ]:
l = [] # create a list

#concate a list to another list
l = l+[10, 20, 30, 'Hello']; #[10, 20, 30, 'Hello']

#extend
l.extend(['a', 'b', 'c']); #[10, 20, 30, 'Hello', 'a', 'b', 'c']

#access an element
print (l[0]) # 10

#append, add an element
l.append(10); #[10, 20, 30, 'Hello', 'a', 'b', 'c', 10]

#count, count of how many times obj occurs
print(l.count(10)) # 2
print(l.count('Hello')) # 1

#index, the lowest index in list that obj appears
print(l.index(10)) # 0

#insert, insert an element at the specific position
l.insert(0, 100); #[100, 10, 20, 30, 'Hello', 'a', 'b', 'c', 10]

#pop, remove the last element
l.pop(); #[100, 10, 20, 30, 'Hello', 'a', 'b', 'c']
print(l)

#remove, remve the first occurance of an object
l.remove('c'); #[100, 10, 20, 30, 'Hello', 'a', 'b']

#reverse, reverse the order
l.reverse(); #['b', 'a', 'Hello', 30, 20, 10, 100]

#sort
# Python 3 only support the sort of same type of objects
l2 = [1, 5, 3, 2]
l2.sort(); # [1, 2, 3, 5]

#repeat a list
l = l*2;

#del
del l[0]; #remove the first 100

l = [x for x in l if x != 20]; #remove all copies of 20

#check length
print(len(l)) # 11

Slicing

In [ ]:
l = list(range(0, 100, 10)) # [0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
print(l)
 
print(l[2]) #20
print(l[-2]) #80

print(l[2:5]) #[20, 30, 40], select element of indices [2, 5)
 
print(l[:2]) #[0, 10]
print(l[7:]) #[70, 80, 90]

Unpacking

In [2]:
#!/usr/bin/python
a, b = [1, 2];
print(a, b) #1 2
1 2

Reference