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.

list