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

How to Define and Initialize a Two-Dimensional Array in Python Without Predefined Lengths?

DDD
Release: 2024-12-13 20:48:35
Original
222 people have browsed it

How to Define and Initialize a Two-Dimensional Array in Python Without Predefined Lengths?

Defining a Two-Dimensional Array Without Initialized Length

When attempting to define a two-dimensional array without specifying its length, you may encounter an "IndexError: list index out of range." This occurs due to the uninitialized outer list.

To resolve this, use Python's "list comprehension" to first initialize the outer list with empty lists:

w, h = 8, 5
Matrix = [[0 for x in range(w)] for y in range(h)] 
Copy after login

This creates a list containing "h" lists of "w" items, all initialized to 0.

Now, you can assign values to the array elements:

Matrix[0][0] = 1
Matrix[6][0] = 3 # error! range... 
Matrix[0][6] = 3 # valid
Copy after login

Note that the array is "y" address major, meaning the "y index" precedes the "x index."

print Matrix[0][0] # prints 1
x, y = 0, 6 
print Matrix[x][y] # prints 3; be careful with indexing! 
Copy after login

Although you can customize the variable names, using "x" and "y" for the inner and outer list indices, respectively, helps avoid confusion with non-square arrays.

The above is the detailed content of How to Define and Initialize a Two-Dimensional Array in Python Without Predefined Lengths?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template