Home > Backend Development > Python Tutorial > How Can I Efficiently Initialize a 2D Array in Python?

How Can I Efficiently Initialize a 2D Array in Python?

Linda Hamilton
Release: 2024-12-04 17:35:12
Original
915 people have browsed it

How Can I Efficiently Initialize a 2D Array in Python?

Initializing a Two-Dimensional Array in Python

When working with Python, you may encounter the need to initialize a two-dimensional array, or a "list of lists." While the provided code snippet utilizing nested loops accomplishes the task, it may not be the most efficient approach.

Simplified Initialization

A more concise way to initialize a two-dimensional array is through list comprehension:

t = [[0] * 3 for i in range(3)]
Copy after login

This code initializes a 3x3 array with all elements set to 0.

A Cautionary Note

While it may seem convenient, using [[v] * n] * n to initialize an array can lead to unexpected behavior. As demonstrated in the code below, this approach creates copies of the same list reference, resulting in references being shared throughout the array:

a = [[0] * 3] * 3
a[0][0] = 1
print(a)  # Output: [[1, 1, 1], [1, 1, 1], [1, 1, 1]]
Copy after login

Unlike expected, all elements of the array become 1. This is because each sublist holds a reference to the original list, and any alteration to one element affects the entire array.

In summary, for initializing two-dimensional arrays in Python, use list comprehension for simplicity and avoid using [[v] * n] * n due to reference sharing issues.

The above is the detailed content of How Can I Efficiently Initialize a 2D Array in Python?. 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