The list is the most flexible and ordered collection object type for Python. Unlike strings, lists are mutable objects. This can be done by specifying offsets and shards, list calls, DELETE statements, and so on.
The list features the following:
An ordered set of arbitrary objects;
Read by offset;
Variable length, heterogeneous and arbitrary nesting;
An array of object references.
Common list operations:
L=[] #创建空列表L =[0,1,2,3] #索引0 -3l=[' abc ', [' def ', ' Ghi ']] #嵌套子列表L =list (' spam ') l=list (RA Nge ( -4,4)) #[-4, -3,-2,-1, 0, 1, 2, 3]l[i]l[i][j]l[i:j]len (L)
Merge operation, the "+" number on both sides must be the same type, otherwise the error will be.
>>>l=[0,1,2,3] >>>l2=[2,3,4,5,6]>>>l + l2[0, 1, 2, 3, 2, 3, 4, 5, 6]>>>STR ([up]) + " "' [1,2]34 ' >>>[1,2] + list (" 34 ")
List Iteration and parsing:
>>>l = [x**2 for x in range (5)] #列表解析 >>>l[0, 1, 4, 9, 16
This expression function is equivalent to manually building a For loop create list, but the encoding for list parsing is simpler and faster to run.
>>>res = []>>>for c in ' spam ' >>>res.append (c*4) >>>res[' ssss ', ' pppp ', ' aaaa ', ' Mmmm ']
Create a new list with the map function:
>>>list (Map (abs,[-1,-2,-4, 0, 3])) [1, 2, 4, 0, 3]
The list of shards, either the first ordinal is 0, or the last ordinal is 0:
>>>l=[' spam ', ' ham ', ' Turkey ']>>>l[2] ' turkey ' >>>l[-2] ' spam ' >>>l[1:][' ham ', ' Turkey ']>>>l[:-1][' spam ', ' ham ']
Two-dimensional arrays:
>>>matrix = [[+], [4,5,6], [7,8,9]]>>>matrix[1][4,5,6]>>>matrix[2][2]9
Modify the list in situ:
>>>l=[' spam ', ' ham ', ' eggs ']>>>l[1]= ' fish ' #单个赋值 >>>l[' spam ', ' fish ', ' eggs ']& gt;>>l[0:2]=[' eat ', ' more '] #分片赋值 the >>>l[' eat ', ' more ', ' eggs ']
>>>l.append (' please ') >>>l[' eat ', ' more ', ' eggs ', ' please ']>>>l.sort () #会原地修改L >> ; >l[' eat ', ' eggs ', ' more ', ' please ']
Note: l.append (' please ') and l+[' please '] results are similar, but the difference is that the former will modify the L in situ, and the latter will generate a new list.
Python Learning: Lists (list)