Home >Backend Development >Python Tutorial >How to Properly Initialize and Index a Two-Dimensional Array in Python?
Defining a Two-Dimensional Array in Python
When initializing a two-dimensional array without specifying the length, you may encounter the error "IndexError: list index out of range." This occurs because Python requires the outer list to be initialized with empty lists before adding any elements.
To resolve this issue, use list comprehension to create the array:
w, h = 8, 5 Matrix = [[0 for x in range(w)] for y in range(h)]
This creates a list containing 5 lists, each with 8 items, all set to zero.
You can then add elements to the array as follows:
Matrix[0][0] = 1 Matrix[6][0] = 3 # error! IndexError: list index out of range Matrix[0][6] = 3 # valid
Note that the matrix is "y" address major, meaning the outer index (y) comes before the inner index (x). This is different from some other programming languages.
For example:
print Matrix[0][0] # prints 1 x, y = 0, 6 print Matrix[x][y] # prints 3; be careful with indexing!
While you can name the indices as you wish, using "x" for the inner and outer lists can lead to confusion when indexing non-square matrices.
The above is the detailed content of How to Properly Initialize and Index a Two-Dimensional Array in Python?. For more information, please follow other related articles on the PHP Chinese website!