How to make a two -dimensional Python array

Create a 2D array in Python with an example: Learn how to create a 2D array in Python and how to use it in your programs.

Creating a Two-Dimensional Array in Python

A two-dimensional array, also known as a two-dimensional matrix, is an array of arrays. It is a data structure where data is stored in a tabular form, in the form of rows and columns. In Python, we can create a two-dimensional array by combining a list of lists into one array.

To create a two-dimensional array in Python, we can use the array() function. This function takes in a list of lists as an argument and returns a two-dimensional array.

import array

# create a two-dimensional array
twoDArray = array.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

# print the array
print(twoDArray)

# output
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

In the above example, we have created a two-dimensional array of size 3x3. The inner lists contain the elements of the array, and the outer list contains the rows of the array.

We can also create a two-dimensional array by using the numpy.array() function from the NumPy library. This function takes in a list of lists as an argument and returns a two-dimensional array.

import numpy

# create a two-dimensional array
twoDArray = numpy.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

# print the array
print(twoDArray)

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

In the above example, we have created a two-dimensional array of size 3x3. The inner lists contain the elements of the array, and the outer list contains the rows of the array.

We can also use the zeros() function to create a two-dimensional array of zeros. This function takes in two arguments: the number of rows and the number of columns, and returns a two-dimensional array filled with zeros.

import numpy

# create a two-dimensional array of zeros
twoDArray = numpy.zeros((3, 3))

# print the array
print(twoDArray)

# output
[[0. 0. 0.]
 [0. 0. 0.]
 [0. 0. 0.]]

In the above example, we have created a two-dimensional array of size 3x3 filled with zeros. The zeros() function takes in two arguments: the number of rows and the number of columns.

We can also use the ones() function to create a two-dimensional array of ones. This function takes in two arguments: the number of rows and the number of columns, and returns a two-dimensional array filled with ones.

import numpy

# create a two-dimensional array of ones
twoDArray = numpy.ones((3, 3))

# print the array
print(twoDArray)

# output
[[1. 1. 1.]
 [1. 1. 1.]
 [1. 1. 1.]]

In the above example, we have created a two-dimensional array of size 3x3 filled with ones. The ones() function takes in two arguments: the number of rows and the number of columns.

In this tutorial, we have seen how to create a two-dimensional array in Python using the array(), numpy.array(), zeros() and ones() functions. We have also seen how to print the elements of the two-dimensional array.

Answers (0)