How to Get List Shape in Python

In this tutorial, we will learn two different ways of getting the shape of a list in Python, the shape being the “rows” and “columns” in a multidimensional list.

Using the len() Function

If we evaluate the length of the whole list and one of the nested lists we can determine its shape.

``````items = [[1,2,3],[4,5,6]]
rows = len(items)
cols = len(items[0])

print(f'Rows: {rows}, Cols: {cols}')
``````
``````Rows: 2, Cols: 3
``````

Using the numpy.shape() Function

NumPy has a `shape()` function that we can use to get the shape of any multidimensional list as a tuple.

``````items = [[1,2,3],[4,5,6]]

print(np.shape(items))
``````
``````(2, 3)
``````

The NumPy solution is probably going to be more reliable when working with lists containing multiple dimensions.

June 30, 2021

October 07, 2020

How to Create and Use Lists (Arrays) in Python

September 01, 2020

How to use Sets in Python

September 15, 2020

March 23, 2021

How to Generate Random Numbers in Python

September 20, 2020