Defining Two-Dimensional Arrays in Python
You may encounter an IndexError when attempting to define a two-dimensional array without initializing its length, as in the syntax:
Matrix = [][]
This error arises because Python requires the outer list to be initialized with inner lists initially. Python refers to this process as "list comprehension," demonstrated in the following code:
# Create a list containing 5 lists, each of 8 items, all set to 0 w, h = 8, 5 Matrix = [[0 for x in range(w)] for y in range(h)]
Once you have initialized the array, you can add items to it. For instance:
Matrix[0][0] = 1 Matrix[6][0] = 3 # error! range... Matrix[0][6] = 3 # valid
Note that the array is "y"-address major, meaning the "y index" precedes the "x index". For example:
print Matrix[0][0] # prints 1 x, y = 0, 6 print Matrix[x][y] # prints 3; be careful with indexing!
To avoid any potential confusion in indexing, consider using "x" for the inner list and "y" for the outer list, especially for non-square arrays.
The above is the detailed content of How Do I Properly Define and Initialize Two-Dimensional Arrays in Python?. For more information, please follow other related articles on the PHP Chinese website!