Home >Backend Development >Python Tutorial >How to Define a Two-Dimensional Array in Python Without Predefined Dimensions?

How to Define a Two-Dimensional Array in Python Without Predefined Dimensions?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-11 10:09:14128browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn