How to define a two-dimensional array?
A two-dimensional array in Python can be defined using the numpy library.
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:
Define a two-dimensional array in Python using numpy library
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]])
<div class="alert alert-info flex not-prose">![]()
<span class="hidden md:block">Watch a video course</span>Python - The Practical Guide</div>
Alternatively, you can create an array filled with zeros with the following code:
Define a two-dimensional array filled with zeros in Python using numpy library
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:
Define a two-dimensional array filled with ones in Python using numpy library
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
Creating a 2D array in Python using list comprehension
two_d_array = [[0 for x in range(3)] for y in range(2)]
print(two_d_array)You can also create 2D array using list() and range()
Creating a 2D array in Python using list() and range()
two_d_array = [list(range(3)) for y in range(2)]
print(two_d_array)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]