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
Release: 2024-12-11 10:09:14
Original
152 people have browsed it

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)]
Copy after login

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
Copy after login

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])
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template