Python list
a.Method for creating a list
1.create list
eg.
>>> a=["python",25,89.9]
>>> a
["python",25,89.9]
2.list index
eg.
>>> a=["python",25,89.9]
>>> a[0]
'python'
>>> a[1]
25
>>> a[2]
89.9
>>> a[-1]
89.9
#get the index in list
>>> a.index(25)
1
>>> a.index(89.9)
2
>>> a.index("python")
0
>>> a.index("blog")
Traceback (most recent call last):
File "<pyshell#26", line 1, in <module>
a.index("blog")
ValueError: 'blog' is not in list
3.list slice(sice([start],stop[,step])
eg.
>>> a=["python",25,89.9]
>>> a[0:2]
['python',25]
>>> a[:1]
['python',25]
>>> a[0:]
["python",25,89.9]
>>> lst= [1,2,3,4,5,6]
>>> lst[::-1]
[6, 5, 4, 3, 2, 1]
>>> lst[0:4]
[1, 2, 3, 4]
>>> lst[0:4:1]
[1, 2, 3, 4]
>>> lst[0:4:2]
[1, 3]
>>> lst[4:1:-1]
[5, 4, 3]
>>> list(reversed(lst))
[6, 5, 4, 3, 2, 1]
>>>len(lst)
6
>>> lst + a
[6, 5, 4, 3, 2, 1,"python", 25, 89.9]
>>> a * 3
["python", 25, 89.9, "python", 25, 89.9, "python", 25, 89.9]
>>> max(lst)
6
>>> min(lst)
1
>>> max(a)
'python'
>>> min(a)
25
>>> cmp(a,lst)
1
b.Common method of list
1.append(object) -- append object to end
eg.
>>> a = [1,2]
>>> a.append(100)
>>> a
[1,2,100]
>>> a.append("python")
>>> a
[1,2,100,'python']
>>> a.append(["google","facebook"])
>>> a
[1,2,100,'python',['google','facebook']]
>>> b = [1]
>>> id(b)
46824863
>>> b.append(5)
>>>b
[1, 5]
>>> id(b)
46824863
2.extend(iterable) -- extend list by appending elements from the iterable
eg.
>>>a = [1, 2, 3]
>>>b = [4, 5, 6]
>>>a.extend(b)
>>>a
>>>[1, 2, 3, 4, 5, 6]
>>>a.extend("python")
>>>a
[1, 2, 3, 4, 5, 6, 'p', 'y', 't', 'h', 'o', 'n']
#Whether the iteration can be judged
>>> hasattr(a,'__iter__')
True
>>> hasattr("python",'__iter__')
False
>>> hasattr(5,'__iter__')
False
3.count(...) integer -- return number of occurrences of value
eg.
>>> a = [1,1,1,2,2,1]
>>> a.count(1)
4
>>> a.count(2)
2
>>> a.count("a")
0
4.index(value, [start, [stop]]) integer -- return first index of value.
eg.
>>> a = [1,1,1,2,2,1]
>>> a.index(1)
0
>>> a.index(2)
3
5.insert(index, object) -- insert object before index
eg.
>>> a = ["python", "web"]
>>> a.insert(1,"qwer")
>>> a
['python', 'qwer', 'web']
>>> a.insert(0,26066913)
>>> a
[26066913,'python', 'qwer', 'web']
6.pop([index]) item -- remove and return item at index (default last)
eg.
>>> a = ["wiki","twitter","google","facebook"]
>>> a.pop(1)
'wiki'
>>> a
['twitter','google','facebook']
>>> a.pop()
'facebook'
>>> a
['twitter','google']
7.remove(value) -- remove first occurrence of value.
eg.
>>> a = ['twitter','twitter','google','facebook']
>>> a.remove("twitter")
>>> a
['twitter','google','facebook']
8.reverse() -- reverse *IN PLACE*
eg.
>>> a=[1,2,3,4]
>>> a.reverse()
>>> a
[4, 3, 2, 1]
9.sort(...)
eg.
>>> a = [5, 3, 9, 2]
>>> a.sort()
>>> a
[2, 3, 5, 9]