Python learning notes-list operations, python learning Notes List
Python List Operation-add
Append: append a piece of data to the end of the list.
Name = ["Zhangsan", "XiongDa", "Lisi"] name. append ("wangwu") print name output result: ['hangsan', 'xiongda', 'lisi', 'hangzhou']
Insert: insert a data entry at a specified position.
Name = ["Zhangsan", "XiongDa", "Lisi"] name. insert (1, "wangwu") # insert a data "wangwu" print name at the position marked as 1. output result: ['hangsan', 'hangzhou', 'xiongda ', 'lisi']
Python List Operation-delete
Name = ["Zhangsan", "XiongDa", "Lisi"] name. remove ("Lisi") # Delete the specified data print name. output result: ['zhangsan', 'xiongda']
Name = ["Zhangsan", "XiongDa", "Lisi"] del name [0] # delete a data print name with a subscript of 0. output result: ['xiongda ', 'lisi']
Name = ["Zhangsan", "XiongDa", "Lisi"] name. pop () # Delete the last data print name output result: ['zhangsan', 'xiongda']
If a parameter is included in pop (), the effect is equivalent to del.
Name.pop(1) == del name[1]
Python List Operation-Modify
Name = ["Zhangsan", "XiongDa", "Lisi"] name [1] = "wangwu" print name output result: ['hangsan ', 'hangw ', 'lisi']
Python list operations-Query
Name = ["Zhangsan", "XiongDa", "Lisi", "wangwu"] print (name [1]) # directly extract the data output result with the subscript of 1: XiongDa
Name = ["Zhangsan", "XiongDa", "Lisi", "wangwu"] print (name [0: 2]) # retrieve data from subscript 0 to subscript 1, the output result does not include 2 (regardless of the end): ['hangsan ', 'xiongda']
When the current value is negative
Name = ["Zhangsan", "XiongDa", "Lisi", "wangwu"] print (name [-1]) # directly extract the data output result with the subscript of 1: wangwu
Name = ["Zhangsan", "XiongDa", "Lisi", "wangwu"] print (name [-3:-1]) # Start from the third to the last, get the second to the last, because the-1 output result is not included: ['xiongda', 'lisi']
Name = ["Zhangsan", "XiongDa", "Lisi", "wangwu"] print (name [-3:]) # Start from the third to the last, get the last output result: ['xiongda', 'lissi', 'wangwu'] Similarly, the name from yesterday [0: 3] = name [: 3]
List other operations:
Name = ["Zhangsan", "XiongDa", "Lisi", "wangwu", "Lisi"] name. count ("Lisi") # count the number of times Lisi appears. clear () # clear Data name. reverse () # reverse the list name. sort () forward sorting name2 = ["1", "2"] name. extend (name2) # merge two arrays, And put name2 behind