Python 2D array

Posted in Python by Dirk - last update: Feb 13, 2024

In Python, a 2D array is essentially a list of lists. It’s a data structure that allows you to store elements in a table or grid-like format with rows and columns. Each element in the 2D array is accessed using two indices: one for the row and another for the column.

Creating a 2D array:

You can create a 2D array using nested lists. Here’s an example:

# Creating a 2D array (3x3 matrix)

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

As you can see - a 2D array is a list of lists

Accessing the values from a 2D array

To access a specific element in the 2D array, you use two indices - one for the row and another for the column:

# Accessing the element in the second row, third column (indexing is zero-based)
value = array[1][2]  # This will be 6

Inserting a value in a 2D array

You can insert values into the 2D array by assigning a value to a specific index:

# Inserting a value at the first row, second column
array[0][1] = 10

Updating values in a 2D array

Updating values is similar to inserting. You just assign a new value to the desired index:

Copy code
# Updating the value in the third row, first column
array[2][0] = 15

Deleting values in a 2D array

# Deleting the value in the second row, second column
del array[1][1]

Example

All operations together:

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

# Accessing value
value = matrix[1][2]  # value is 6

# Inserting value
matrix[0][1] = 10

# Updating value
matrix[2][0] = 15

# Deleting value
del matrix[1][1]

After these operations, matrix will be :

[
    [1, 10, 3],
    [4, 6],  # Value at [1][1] deleted
    [15, 8, 9]
]

Note: 2D array in Python does not necessarily have to have an equal number of elements in each row. Unlike a matrix, which is a specific type of 2D array with equal-sized rows and columns, a general 2D array can have rows of varying lengths.

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

In this example, the first row has three elements, the second row has two elements, the third row has four elements, and the fourth row has one element. This is a valid representation of a 2D array in Python.

However, when working with mathematical operations or matrix-like structures, it’s common to use matrices where each row has the same number of elements for consistency and ease of computation.

Alternatives for arrays

Python, lists of lists are a common and flexible way to work with 2D arrays. However, depending on the specific requirements of your task, there are other tools and libraries that might offer better performance, convenience, or additional functionality.

NumPy:

NumPy is a powerful library for numerical and scientific computing in Python. It provides a multidimensional array object (numpy.ndarray) that is more efficient than Python lists for numerical operations. NumPy arrays have a fixed size at creation, which can lead to better performance compared to dynamic resizing of lists.

import numpy as np

matrix = np.array([
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
])

NumPy provides a wide range of functions for array manipulation, mathematical operations, and linear algebra.

Pandas

Pandas is a powerful data manipulation library that provides a DataFrame object, which can be thought of as a 2D table. It’s particularly useful for handling labeled data and working with datasets.


import pandas as pd

df = pd.DataFrame({
    'A': [1, 4, 7],
    'B': [2, 5, 8],
    'C': [3, 6, 9]
})

Pandas DataFrames offer many convenient features for data analysis and manipulation.

2D arrays vs Numpy arrays vs Pandas

The choice between using plain lists of lists, NumPy arrays, or Pandas DataFrames depends on your specific use case. If you’re working with numerical data and need performance, NumPy is often a good choice. If you’re dealing with labeled data and want more data manipulation capabilities, Pandas is a great option. For general purposes, lists of lists may be sufficient and more straightforward.

Other articles