How to make a two -dimensional array in Python

Create a 2D array in Python with code example: Learn how to declare, initialize, and access elements of a two-dimensional array in Python.

A two-dimensional array is an array with two dimensions, such as a matrix. In Python, we can create such an array using a nested list. A nested list is a list inside another list. To create a two-dimensional array, we can nest a list inside a list like this:


two_dimensional_array = [[1, 2, 3],
                        [4, 5, 6],
                        [7, 8, 9]]

The above array is a 3x3 two-dimensional array. The first list inside the outer list contains the elements 1, 2, and 3. The second list inside the outer list contains the elements 4, 5, and 6. The third list contains the elements 7, 8, and 9.

Accessing items in a two-dimensional array

We can access elements in the two-dimensional array using two indices. The first index specifies the row and the second index specifies the column. For example, we can access the element 7 in the above array like this:


two_dimensional_array[2][0]
# Output: 7

Here, the first index 2 specifies the third list in the array, and the second index 0 specifies the first element in the third list. If you are familiar with mathematical matrices, you can think of the two indices as the row and column numbers of the matrix.

Answers (0)