List operations
List function:
[Python] View PlainCopy
- >>> list (' Hello ')
- [' h ', ' e ', ' l ', ' l ', ' o ']
Change the list:
[Python] View PlainCopy
- >>> x=[1,1,1]
- >>> x[1]=2
- >>> x
- [1, 2, 1]
To delete an element:
[Python] View PlainCopy
- >>> names = [' Wu ',' Li ', 'Zhao ',' Qian ']
- >>> del names[1]
- >>> names
- [' Wu ', ' Zhao ', ' Qian ']
Shard Assignment:
[Python] View PlainCopy
- >>> name = List (' perl ')
- >>> Name
- [' P ', ' e ', ' R ', ' l ']
- >>> name[2:] = list (' ar ')
- >>> Name
- [' P ', ' e ', ' a ', ' R ']
[Python] View PlainCopy
- >>> num = [1,2,3,4,5]
- >>> num[1:4]=[] # starts with 1 bits but does not include 4-bit
- >>> num
- [1, 5]
Add a new element at the end of the Append list:
[Python] View PlainCopy
- >>> LST = [1,2,3]
- >>> Lst.append (4)
- >>> LST
- [1, 2, 3, 4]
Number of Count statistics elements:
[Python] View PlainCopy
- >>> [' we ',' have ',' we ', 'a ',' dog '].count (' we ')
- 2
Extend extension list:
[Python] View PlainCopy
- >>> a = [1,2,3]
- >>> B = [4,5,6]
- >>> A.extend (b)
- >>> A
- [1, 2, 3, 4, 5, 6]
Index to find the location of the first occurrence:
[Python] View PlainCopy
- >>> sentence = [' I ',' have ',' a ',' little ',' dog ']
- >>> Sentence.index (' little ')
- 3
Insert inserts an object into the list:
[Python] View PlainCopy
- >>> 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 last one by default:
[Python] View PlainCopy
- >>> x = [1,2,3]
- >>> X.pop ()
- 3
- >>> x
- [1, 2]
- >>> X.pop (0)
- 1
- >>> x
- [2]
Combined Append:
[Python] View PlainCopy
- >>> x = [1,2,3]
- >>> X.append (X.pop ())
- >>> x
- [1, 2, 3]
Remove removes the first occurrence from the list:
[Python] View PlainCopy
- >>> x = [' to ',' is ', 'or ',' not ',' to ',' is ']
- >>> x.remove (' be ')
- >>> x
- [' to ', ' or ', ' no ', ' to ', ' being ']
Reverse Reverse storage elements:
[Python] View PlainCopy
- >>> x = [1,2,3]
- >>> X.reverse ()
- >>> x
- [3, 2, 1]
Sort order:
[Python] View PlainCopy
- >>> x = [4,6,2,1,7,9]
- >>> X.sort ()
- >>> x
- [1, 2, 4, 6, 7, 9]
[Python] View PlainCopy
- >>> X.sort (reverse=True)
- >>> x
- [9, 7, 6, 4, 2, 1]
- >>> X.sort (reverse=False)
- >>> x
- [1, 2, 4, 6, 7, 9]
Beginning Python from Novice to Professional (3)-list operation