Initialization of one-dimensional list :
Initialization of two-dimensional list :
Initialization of one-dimensional list :The initial length is 5 A list of
The way 1:
a = [0]*5# [0, 0, 0, 0, 0]
The way 2:
a = [0 for _ in range(5)]# [0, 0, 0, 0, 0]
Initialization of two-dimensional list :The first one 2*5 A list of :
The way 1:
b = [[0]*5 for _ in range(2)]# [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
The way 2:
b = [[0 for _ in range(5)] for _ in range(2)]# [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
Be careful :
The following is wrong , This is equivalent to taking [0]*5 This one-dimensional list duplicates 2 Time , Whenever you change an element in one of the one-dimensional lists , The elements in the rest of the list will also change .
b = [[0]*5]*2# [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]b[0][1] = 3 # [[0, 3, 0, 0, 0], [0, 3, 0, 0, 0]]
This is about python ( A one-dimensional 、 A two-dimensional ) This is the end of the list initialization article , More about python For the initialization content of the list, please search the previous articles of the software development network or continue to browse the relevant articles below. I hope you can support the software development network in the future !