How to Create a 2D Array in Python?

As a Python developer, I faced challenges handling multi-dimensional data structures and making a 2D array. In this tutorial, I will explain how to create and manipulate 2D arrays in Python. I explored various ways to achieve this task, I will show important methods with examples and screenshots of executed example code.

Python 2D Array

A 2D array, or a matrix, is a collection of data elements arranged in rows and columns. It is a list of lists, where each sublist represents a row. This structure is good for representing grids, tables, and other two-dimensional data.

Read How to Convert Python Dict to Array

Create a 2D Array in Python

Python supports various ways to create a 2D array.

Method 1. Use Nested Lists

The simple way to create a 2D array is by using nested lists. Here’s an example:

# Creating a 2D array using nested lists
city_temperatures = [
    ["New York", 55, 60, 65],
    ["Los Angeles", 75, 78, 80],
    ["Chicago", 50, 55, 60],
    ["Houston", 70, 75, 80]
]

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

Output:

New York
50

You can see the executed example code in the below screenshot.

Make a 2D Array in Python

In this example, city_temperatures is a 2D array where each sublist represents a city and its temperatures over three days.

check out How to Sort an Array in Python

Method 2. Use List Comprehensions

List comprehensions provide an easy way to create 2D arrays. Here’s how you can use them:

# Creating a 2D array using list comprehensions
rows, cols = 4, 3
matrix = [[0 for _ in range(cols)] for _ in range(rows)]

# Populating the matrix with sample data
for i in range(rows):
    for j in range(cols):
        matrix[i][j] = i * j

print(matrix)

Output:

[[0, 0, 0], [0, 1, 2], [0, 2, 4], [0, 3, 6]]

You can see the executed example code in the below screenshot.

How to Make a 2D Array in Python

This code creates a 4×3 matrix filled with zeros and then populates it with the product of the row and column indices.

Read How to Use Python Array Index -1

Method 3. Use NumPy

NumPy library in Python is used for numerical computing. It provides efficient methods to create and manipulate 2D arrays. Here’s an example:

import numpy as np

# Creating a 2D array using NumPy
city_temperatures = np.array([
    ["New York", 55, 60, 65],
    ["Los Angeles", 75, 78, 80],
    ["Chicago", 50, 55, 60],
    ["Houston", 70, 75, 80]
])

# Accessing elements
print(city_temperatures[0, 0]) 
print(city_temperatures[2, 1])  

Output:

New York
50

You can see the executed example code in the below screenshot.

Make a 2D Array in Python Use NumPy

NumPy arrays are more efficient and provide more functionality than nested lists.

Check out How to Save an Array to a File in Python

Access and Modify Elements

Accessing elements in a 2D array is easy. You can use row and column indices to access specific elements. Here’s an example:

# Accessing and modifying elements in a 2D array
city_temperatures = [
    ["New York", 55, 60, 65],
    ["Los Angeles", 75, 78, 80],
    ["Chicago", 50, 55, 60],
    ["Houston", 70, 75, 80]
]

# Accessing an element
print(city_temperatures[1][2])  

# Modifying an element
city_temperatures[1][2] = 79
print(city_temperatures[1][2])  

Output:

78
79

Read How to Find the Number of Elements in a Python Array

Example: Weather Data Analysis

Let’s consider a real-world example where we analyze weather data from different cities in the USA. We will create a 2D array to store the data and perform basic analysis.

1. Create the 2D Python Array

import numpy as np

# Creating a 2D array with weather data
weather_data = np.array([
    ["City", "Day 1", "Day 2", "Day 3"],
    ["New York", 55, 60, 65],
    ["Los Angeles", 75, 78, 80],
    ["Chicago", 50, 55, 60],
    ["Houston", 70, 75, 80]
])

2. Calculate Average Temperature

# Calculating the average temperature for each city
for row in weather_data[1:]:
    city = row[0]
    temps = row[1:].astype(int)
    avg_temp = np.mean(temps)
    print(f"Average temperature in {city} over 3 days: {avg_temp:.2f}°F")

3. Find the Hottest and Coldest Days

# Finding the hottest and coldest days for each city
for row in weather_data[1:]:
    city = row[0]
    temps = row[1:].astype(int)
    hottest_day = np.argmax(temps) + 1
    coldest_day = np.argmin(temps) + 1
    print(f"In {city}, the hottest day is Day {hottest_day} and the coldest day is Day {coldest_day}.")

You can learn how to iterate over a 2D array in Python from this tutorial How to Iterate Through a 2D Array in Python

Conclusion

In this tutorial, I explained how to create and manipulate 2D arrays in Python. I gave an introduction to 2D arrays in Python and various methods to create Python 2D arrays like using nested lists, list comprehension, and using NumPy. I explained how to access and modify elements, and we also discussed example weather data analysis, for creating a 2D Python array, calculating average temperature and finding the hottest and coldest days.

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.