Introduction to the list and common operations

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
Insert picture description here
another collection to the list one by one through extend.
Insert picture description here
Insert picture description here
insert(index, object) Insert the element object before the specified position index
Insert picture description here
. When modifying the element, use the subscript Determine which element is to be modified, and then modify the
Insert picture description here
search element ("check" in, not in, index, count) The
so-called search is to see if the specified element exists
in, not in

Insert picture description here
not in
Insert picture description here
<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

Insert picture description here

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.
Insert picture description here

Nesting of lists

Nesting of lists

  1. 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']]

Guess you like

Origin blog.csdn.net/CHINA_2000chn/article/details/108585267