Introduction to the list
The format of the list: the type of variable A is the list
namesList = ['xiaoWang','xiaoZhang','xiaoHua']
The more powerful than the C language array is that the elements in the list can be different types of
testList = [1,'a']
1. Use a for loop
In order to output each data in the list more efficiently, you can use a loop to complete
demo:
namesList = ['xiaoWang','xiaoZhang','xiaoHua']
for name in namesList:
print(name)
Result:
xiaoWang
xiaoZhang
xiaoHua
2. Use a while loop
In order to output each data in the list more efficiently, you can use a loop to complete the
demo:
namesList = ['xiaoWang','xiaoZhang','xiaoHua']
length = len(namesList)
i = 0
while i <length:
print(namesList[i])
i+=1
Result:
xiaoWang
xiaoZhang
xiaoHua
List related operations
You can add elements to the list (tail) through append. You can add elements in
another collection to the list one by one through extend.
insert(index, object) Insert the element object before the specified position index
. When modifying the element, use the subscript Determine which element is to be modified, and then modify the
search element ("check" in, not in, index, count) The
so-called search is to see if the specified element exists
in, not in
not in
<4> delete the element ("Delete" del, pop, remove)
Analogy in real life, if a classmate is transferred, then the name of the student after this entry should be deleted; this function is often used in development.
Common ways to delete list elements are:
del: delete according to the subscript
pop: delete the last element
remove: delete according to the value of the element
Sort (sort, reverse)
The sort method is to rearrange the list in a specific order, the default is from small to large, the parameter reverse=True can be changed to reverse order, from large to small.
The reverse method is to reverse the list.
Nesting of lists
Nesting of lists
- Nested list
Nested similar while loop, also supports nested list of
a list element is a list, then this is the list of nested
schoolNames = [[ 'Peking', 'Tsinghua University'],
[ ' Nankai University','Tianjin University','Tianjin Normal University'],
['Zhejiang University'],['Hebei University','Hebei University of Science and Technology']]