Beginning Python From Novice to Professional (3)-List Operation, pythonnovice
List operations
List function:
>>> list('hello')['h', 'e', 'l', 'l', 'o']
Change List:
>>> x=[1,1,1]>>> x[1]=2>>> x[1, 2, 1]
Delete element:
>>> names = ['wu','li','zhao','qian']>>> del names[1]>>> names['wu', 'zhao', 'qian']
Partition assignment:
>>> name = list('perl')>>> name['p', 'e', 'r', 'l']>>> name[2:] = list('ar')>>> name['p', 'e', 'a', 'r']
>>> Num = [1, 3, 4, 5] >>> num [] = [] # Starts from 1 bit but does not include 4 digits >>> num [1, 5]
Add new elements at the end of the append list:
>>> lst = [1,2,3]>>> lst.append(4)>>> lst[1, 2, 3, 4]
Count:
>>> ['we','have','we','a','dog'].count('we')2
Extend extension list:
>>> a = [1,2,3]>>> b = [4,5,6]>>> a.extend(b)>>> a[1, 2, 3, 4, 5, 6]
Index to locate the first matching item:
>>> sentence = ['I','have','a','little','dog']>>> sentence.index('little')3
Insert inserts an object into the list:
>>> num = [1,2,3,5,6,7]>>> num.insert(3,'four')>>> num[1, 2, 3, 'four', 5, 6, 7]
Pop removes the list element. The default is the last one:
>>> x = [1,2,3]>>> x.pop()3>>> x[1, 2]>>> x.pop(0)1>>> x[2]
Combined with append:
>>> x = [1,2,3]>>> x.append(x.pop())>>> x[1, 2, 3]
Remove the first match from the list:
>>> x = ['to','be','or','not','to','be']>>> x.remove('be')>>> x['to', 'or', 'not', 'to', 'be']
Reverse storage elements:
>>> x = [1,2,3]>>> x.reverse()>>> x[3, 2, 1]
Sort by sort:
>>> x = [4,6,2,1,7,9]>>> x.sort()>>> x[1, 2, 4, 6, 7, 9]
>>> x.sort(reverse=True)>>> x[9, 7, 6, 4, 2, 1]>>> x.sort(reverse=False)>>> x[1, 2, 4, 6, 7, 9]