Creating a 2D array in Python is a defined data structure that represents a two-dimensional grid or matrix. A 2D array consists of rows and columns, forming a tabular structure where each element is uniquely identified by its row and column indices.
array_2d = [[element1, element2, element3], [element4, element5, element6], [element7, element8, element9]]
In Python, you can create a 2D array using nested lists or by utilizing libraries such as NumPy. Using nested lists, each row of the 2D array is represented as a separate list, and these lists are nested within another list to form the 2D structure. Alternatively, NumPy provides a specialized array object that efficiently handles multi-dimensional arrays, including 2D arrays.
Create a 2D array in Python example
To create a 2D array in Python, you can use nested lists or NumPy library. Here’s how you can do it using both methods:
Using Nested Lists:
# Method 1: Using nested lists
rows = 3 # Number of rows
cols = 4 # Number of columns
# Creating a 2D array (nested list)
array_2d = [[0] * cols for _ in range(rows)]
# Accessing and modifying elements in the 2D array
array_2d[0][0] = 1 # Set element at row 0, column 0 to 1
array_2d[1][2] = 2 # Set element at row 1, column 2 to 2
print(array_2d)
Using NumPy: If you have the NumPy library installed, you can use the numpy.array
function to create a 2D array.
import numpy as np
# Method 2: Using NumPy
rows = 3 # Number of rows
cols = 4 # Number of columns
# Creating a 2D array using NumPy
array_2d = np.zeros((rows, cols))
# Accessing and modifying elements in the 2D array
array_2d[0, 0] = 1 # Set element at row 0, column 0 to 1
array_2d[1, 2] = 2 # Set element at row 1, column 2 to 2
print(array_2d)
Output:
Once created, you can access and modify individual elements of a 2D array using indexing, specifying the row and column indices. This allows you to perform various operations and computations on the data stored in the 2D array, making it a versatile data structure for many applications in Python programming.
Comment if you have any doubts or suggestions on this Python Array topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.