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)]
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]]
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!