The list in Python, similar to vertor in C + +, supports random access and can dynamically add or delete data, but the list is more flexible than vector and can hold any type of element, including nested lists.
1. List creation: use [] to denote that the elements are separated by parentheses.
List1 = [' A ', ' B ', ' C ']
2. Access the elements in the list:
#通过下标遍历listfor i in range (len (list1)): print List1[i] #通过for迭代listfor v in List1:print (v)
The elements in the list are accessed directly by subscript, like the C language array, and the subscript is starting from 0.
#修改list中的元素list1 [0] = ' ab ' Print (list1) >>> [' Ab ', ' B ', ' C ']
To delete an element in the list:
Del list1[1]print (List1) >>> [' Ab ', ' C ']
List is can be dynamically added with the deletion of elements, the increase is not as simple as deleting, such as:
#像list尾部插入一个元素list1 [Len (list1)] = ' d ' Traceback (most recent call last): File "<pyshell#19>", line 1, in <module& Gt List1[len (list1)] = ' d ' indexerror:list Assignment index out of range
Note that inserting an element cannot be done directly, either through an insert or a append method:
#从尾部插入list1. Append (' d ') print (list1) >>> [' Ab ', ' C ', ' d '] #在指定位置插入list1. Insert (1, ' E ') print (List1) >> > [' ab ', ' e ', ' C ', ' d ']list1.insert (+, ' x ') print (list1) >>> [' AB ', ' e ', ' C ', ' d ', ' X ']
From the above results, when the Insert method is inserted at the specified position, the element and its subsequent elements are moved if the specified position already has an element. If the specified position exceeds the end position, the element is inserted into the trailer.
3. Intercept some elements of list: This is the same as a tuple, [Left:right, step], left closed, right open
Print (List1[1:3]) >>> [' E ', ' C ']print (List1[1:-1]) >>> [' E ', ' C ', ' d ']
4. Other common methods in the list:
1) reverse (): Reverse list
List1.reverse () print (list1) >>> [' X ', ' d ', ' C ', ' e ', ' AB ']
2) Remove (value): Removes the first value in the list that matches the element of value
List1.remove (' ab ') print (list1) >>> [' X ', ' d ', ' C ', ' e ']
3) Pop (): Removes the last element in the list and returns it
printf (List1.pop ()) >>> ' E ' Print (list1) >>> [' X ', ' d ', ' C ']
4) count (value): The number of elements in the list that are equal to value
List1.count (' a ') >>> 0list1.count (' x ') >>> 1
5) Sort (func): Sort the elements of a list
List1.sort () print (list1) >>> [' C ', ' d ', ' X ']
6) Index (value): Finds the first element that matches value, returns its index value
List1.index (' d ') >>> 1
If you simply determine whether an element exists in the list, you can use in to determine
If ' d ' in List1:print (' d are in List1 ') else:print (' d ' are not in List1 ') >>> D are in List1
Getting Started with Python (vi) List