How to define a two-dimensional array?
A two-dimensional array in Python can be defined using the numpy
library. Here is an example of how to define a 2x3 (2 rows and 3 columns) array:
import numpy as np
# define a 2x3 array with values [1, 2, 3], [4, 5, 6]
two_d_array = np.array([[1, 2, 3], [4, 5, 6]])
Watch a video course
Python - The Practical Guide
Alternatively, you can create an array filled with zeros with the following code:
import numpy as np
# create a 2x3 array filled with zeroes
two_d_array = np.zeros((2,3))
You can also create an array filled with ones:
import numpy as np
# create a 2x3 array filled with ones
two_d_array = np.ones((2,3))
Another way of creating a 2D array is using python's list comprehension
You can also create 2D array using list() and range()
Please note that in python, arrays are zero-indexed, so the first element of the array is at two_d_array[0][0]
and the last element of the array is at two_d_array[1][2]