For high-performance Python programs, the array module is a good choice. Often 2D data benefits from the array module. We develop a 2D array.
With index expressions, we can convert 2 indexes into a single index. Thus we use a 1D array in memory as a 2D array. Some special logic is needed.
Here is an example program that creates a 2D array of 10 by 10 integer elements. It receives console input. We provide 3 values to it.
Value1
is the X coordinate. This can be a number between 0 and 9 inclusive.Value2
is the Y coordinate. When accessing the array, we multiply this by the array's X dimension, which is 10 here.Value3
is the value we want to set in the 2D array. The integer that exists is printed to the console before it is changed.from array import array # Create an int array. integers = array("i") # Add 100 elements for a 10 by 10 array. # ... We can address each element by a single index. for i in range(100): integers.append(0) while(True): print("2D array has dimensions 10x10") print("Type 3 values:") print(" X, Y, and value to set") print(" Current value will be printed") # Get input. values = input() # Split on comma. separated = values.split(",") # Parse arguments into numbers. value1 = int(separated[0]) value2 = int(separated[1]) value3 = int(separated[2]) # Access array with 2 coordinates. # ... Multiply the Y by 10 to convert to 1 index. current = integers[(value2 * 10) + value1] print("CURRENT: " + str(current)); # Update with new value. integers[(value2 * 10) + value1] = value3;2D array has dimensions 10x10 Type 3 values: X, Y, and value to set Current value will be printed 5,5,10 CURRENT: 0 2D array has dimensions 10x10 Type 3 values: X, Y, and value to set Current value will be printed 5,5,15 CURRENT: 10 2D array has dimensions 10x10 Type 3 values: X, Y, and value to set Current value will be printed 5,5,30 CURRENT: 15 2D array has dimensions 10x10 Type 3 values: X, Y, and value to set Current value will be printed 0,5,200 CURRENT: 0 2D array has dimensions 10x10 Type 3 values: X, Y, and value to set Current value will be printed 0,5,300 CURRENT: 200 2D array has dimensions 10x10 Type 3 values: X, Y, and value to set Current value will be printed
In benchmarks, the array module is much faster and requires much less memory than Lists. So for 2D data, a flattened 2D array would be a good choice.
In this program, we read and write elements from a 2D array of integers. The array stores values in memory accessed by an X and Y coordinate.