How to Create a 2D Array in Python

To create a 2D array in Python, you can use the numpy.array() function to create an array from a list, and also use the numpy.zeros() and numpy.ones() functions to create arrays of zeros and ones, respectively.

The following examples show how to create a 2D array in Python using these three methods:

Using numpy.array() Function

We can use the numpy.array() function to create a 2D array from lists.

Suppose we have the following lists:

import numpy as np

# Declare lists
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = [7, 8, 9]

# Create 2D array
array_2d = np.array([list1, list2, list3])

# Show array
print(array_2d)

Output: 👇️

[[1 2 3]
 [4 5 6]
 [7 8 9]]

In this example, we use the numpy.array() function to create a 2D array array_2d from the lists list1, list2, and list3.

The output shows the 2D array created using the numpy.array() function.

Using numpy.zeros() Function

We can use the numpy.zeros() function to create a 2D array of zeros.

Suppose we have the following dimensions:

import numpy as np

# Declare count of rows and columns
rows = 3
columns = 3

# Create array of zeros
zeros_2d = np.zeros((rows, columns))

# Show array of zeros
print(zeros_2d)

Output: 👇️

[[0. 0. 0.]
 [0. 0. 0.]
 [0. 0. 0.]]

In this example, we use the numpy.zeros() function to create a 2D array zeros_2d of zeros with the specified number of rows and columns.

The output shows the 2D array of zeros created using the numpy.zeros() function.

Using numpy.ones() Function

We can use the numpy.ones() function to create a 2D array of ones.

Suppose we have the following dimensions:

import numpy as np

# Declare count of rows and columns
rows = 3
columns = 3

# Create array of ones
ones_2d = np.ones((rows, columns))

# Show array of ones
print(ones_2d)

Output: 👇️

[[1. 1. 1.]
 [1. 1. 1.]
 [1. 1. 1.]]

In this example, we use the numpy.ones() function to create a 2D array ones_2d of ones with the specified number of rows and columns.

The output shows the 2D array of ones created using the numpy.ones() function.

Conclusion

We can use the numpy.array() function to create a 2D array from lists, and the numpy.zeros() and numpy.ones() functions to create 2D arrays of zeros and ones, respectively, in Python.