How to get shape of an array in python
Published on Aug. 22, 2023, 12:16 p.m.
To get the shape of an array in Python, you can use the shape
attribute for numpy arrays or the shape
method for regular Python lists. Here are some examples:
For a numpy array:
import numpy as np
my_array = np.array([[1, 2, 3], [4, 5, 6]])
print(my_array.shape)
This will output (2, 3)
, which indicates that the array has 2 rows and 3 columns.
For a regular Python list:
my_list = [[1, 2], [3, 4], [5, 6]]
n_rows = len(my_list)
n_cols = len(my_list[0])
print((n_rows, n_cols))
This will output (3, 2)
, which indicates that the list has 3 rows and 2 columns.
In both cases, the shape
information is returned as a tuple, where the first element represents the number of rows and the second element represents the number of columns (or dimensions for numpy arrays with more than 2 dimensions).
Note that the shape
attribute and method are read-only, so you cannot change the shape of an array or list using them.