Home >Backend Development >Python Tutorial >How to Define a Two-Dimensional Array in Python Without Predefined Dimensions?
Defining a Two-Dimensional Array without an Initialized Length
To define a two-dimensional array without an initialized length, it is necessary to first initialize the outer list with lists using list comprehension:
# Creates 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 the outer list is initialized, individual values can be added to the array:
# Adds 1 to the top-left corner of the array, and 3 to the bottom-right Matrix[0][0] = 1 Matrix[h - 1][0] = 3 # Error! Index out of range Matrix[0][w - 1] = 3
Note that the array is "y" address major, meaning the "y index" comes before the "x index" when accessing elements:
# Prints 1 from the top-left corner print(Matrix[0][0]) # Prints 3 from the bottom-right corner x, y = 0, w - 1 print(Matrix[x][y])
While the inner and outer lists can be named arbitrarily, it is recommended to use different names to avoid confusion during indexing, especially when dealing with non-square arrays.
The above is the detailed content of How to Define a Two-Dimensional Array in Python Without Predefined Dimensions?. For more information, please follow other related articles on the PHP Chinese website!