Skip to content

Python initialize 2d array

  • by

In Python, you can initialize a 2D array using nested lists or by using NumPy’s array object. To initialize a 2D array in Python using nested lists, you can use the following syntax:

rows = 3
cols = 4

# Initialize a 2D array filled with zeros
array = [[0] * cols for _ in range(rows)]

If you want to initialize the 2D array with custom values, you can modify the syntax accordingly:

# Initialize a 2D array with custom values
custom_array = [[1, 2, 3, 4],
                [5, 6, 7, 8],
                [9, 10, 11, 12]]

Python initialize 2d array example

To initialize a 2D array in Python, you can use nested lists or NumPy arrays. Here are examples of both approaches:

Using nested lists:

# Initialize a 2D array using nested lists
rows = 3
cols = 4

# Method 1: Initialize with a default value (e.g., 0)
array = [[0] * cols for _ in range(rows)]

# Method 2: Initialize with different values
array = [[1, 2, 3, 4],
         [5, 6, 7, 8],
         [9, 10, 11, 12]]

In the nested list approach, you create a list of lists. Each inner list represents a row in the 2D array. You can initialize the elements with a default value (e.g., 0) or specify custom values for each element.

Using NumPy:

import numpy as np

# Initialize a 2D array using NumPy
rows = 3
cols = 4

# Method 1: Initialize with a default value (e.g., 0)
array = np.zeros((rows, cols))

# Method 2: Initialize with different values
array = np.array([[1, 2, 3, 4],
                  [5, 6, 7, 8],
                  [9, 10, 11, 12]])

print(array)

With NumPy, you can use the zeros function to initialize the array with a default value (e.g., 0). Alternatively, you can use the array function to create an array with custom values.

Output:

Python initialize 2d array

Both methods will give you a 2D array that you can access and manipulate using indexing.

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.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading