Home >Backend Development >Python Tutorial >How to Properly Initialize and Use Two-Dimensional Arrays in Python Without Predefined Dimensions?
Defining Two-Dimensional Arrays in Python Without Initialized Length
When attempting to define a two-dimensional array in Python without specifying the length, such as:
Matrix = [][]
you may encounter an "IndexError: list index out of range" error. To resolve this, it's necessary to initialize the outer list with empty lists before adding any items. Python utilizes a technique called list comprehension for this purpose.
Consider the following code:
w, h = 8, 5 Matrix = [[0 for x in range(w)] for y in range(h)]
Here, we've created a list of 5 lists, each containing 8 zeros. Now, you can add items to this array:
Matrix[0][0] = 1 Matrix[6][0] = 3 # error! out of range Matrix[0][6] = 3 # valid
Note that the matrix is "y" address major, meaning the "y index" precedes the "x index." For instance:
print Matrix[0][0] # prints 1 x, y = 0, 6 print Matrix[x][y] # prints 3
It's important to be careful with indexing and avoid using the same variable name (e.g., "x") for both the inner and outer lists when working with non-square matrices.
The above is the detailed content of How to Properly Initialize and Use Two-Dimensional Arrays in Python Without Predefined Dimensions?. For more information, please follow other related articles on the PHP Chinese website!