How to Initialize a 2D Array in Python?

In this tutorial, I will explain how to initialize a two-dimensional (2D) array in Python. As a developer working on various projects in the USA, I have encountered situations where using 2D arrays was essential. I explored multiple ways to initialize a 2D array, Let us see the important methods with examples and screenshots of executed example code.

Python 2D Array

Before initializing a 2D array, let’s understand the 2D array in Python. This is known as a matrix and a collection of elements arranged in rows and columns. It can be a list of lists, where each inner list represents a row in the matrix.

Read Python program to print the smallest element in an array

Initialize a 2D Array in Python

2D array initialization in Python can be done in various ways, Let us see important methods.

Method 1. Use Nested Lists

One of the simple ways to initialize a 2D array in Python is by using nested lists. This approach involves creating a list of lists, where each inner list represents a row in the matrix. Here’s an example:

students = [
    ["John", "New York", 85],
    ["Emily", "California", 92],
    ["Michael", "Texas", 78]
]
print(students)

Output:

[['John', 'New York', 85], ['Emily', 'California', 92], ['Michael', 'Texas', 78]]

I executed the above example code and added its screenshot below.

Initialize a 2D Array in Python

In this example, a 2D array students represents a list of students with their names, locations, and grades. Each inner list corresponds to a row in the matrix.

To access elements in a 2D array, you use two indices, the first index refers to the row, and the second to the column. To access Emily’s grade, you would use students[1][2], which retrieves the element at row 1 and column 2.

Check out How to Split a String into an Array in Python

Method 2. Initialize Fixed Size Python Array Using List Comprehensions

Sometimes, you may need to initialize a 2D array of fixed size, where all elements are initially set to a default value. Python provides a concise way to achieve this using list comprehensions. Here’s an example:

num_rows = 3
num_cols = 4
sales = [[0 for _ in range(num_cols)] for _ in range(num_rows)]
print(sales)

Output:

[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

I executed the above example code and added its screenshot below.

How to Initialize a 2D Array in Python

In this example, we initialize a 2D array sales with 3 rows and 4 columns, where all elements are initially set to 0.

Read 3D Arrays in Python

Method 3. Use NumPy

When working with large 2D arrays or performing complex mathematical operations it is efficient to use Python NumPy. Here’s an example of initializing a 2D array using NumPy:

import numpy as np

temperatures = np.array([
    [72, 75, 71, 68],
    [81, 79, 83, 77],
    [69, 72, 75, 73]
])
print(temperatures)

Output:

[[72 75 71 68] 
 [81 79 83 77] 
 [69 72 75 73]]

I executed the above example code and added its screenshot below.

Initialize a 2D Array in Python Use NumPy

In this example, we create a 2D array called temperatures using NumPy’s array() function.

Check out How to Print Duplicate Elements in Array in Python

Access and Modify Elements in a 2D Array in Python

Once you have initialized a 2D array, you can access and modify its elements using the row and column indices. Here’s an example:

students = [
    ["John", "New York", 85],
    ["Emily", "California", 92],
    ["Michael", "Texas", 78]
]

# Accessing elements
print(students[0][0])  
print(students[1][2])  

# Modifying elements
students[2][1] = "Florida"
students[1][2] = 95

Output:

John
92

In this example, we access elements from the students array using the row and column indices. We can also modify elements by assigning new values to specific positions.

Read How to Convert an Array to a Tuple in Python

Iterate over a 2D Array in Python

To process the elements of a 2D array, you can use nested loops to iterate over the rows and columns. Here’s an example:

sales = [
    [1200, 1500, 1800, 1100],
    [2000, 1800, 2200, 1900],
    [1500, 1700, 1600, 1400]
]

for row in sales:
    for amount in row:
        print(amount, end=" ")
    print()

In this example, we use nested for loops to iterate over the sales array. The outer loop iterates over the rows, while the inner loop iterates over the elements within each row. We print each element followed by a space, and we use print() without any arguments to move to the next line after each row.

You can also read how to iterate through a 2D array by various methods in this tutorial How to Iterate Through a 2D Array in Python

Conclusion

In this tutorial, I have explained how to initialize a two-dimensional (2D) array in Python. I gave an introduction to Python 2D arrays, and explained methods like using nested lists, initializing fixed size Python array using list comprehensions, using NumPy. We also discussed how to access and modify elements in 2D Python array, and how to iterate over a 2D array in Python.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.