Get List Shape in Python

Get the Shape of a List With the
len()
Function in Python 
Get the Shape of a List With the
numpy.shape()
Method in Python
In this tutorial, we will discuss methods to get the shape of a list in Python.
Get the Shape of a List With the len()
Function in Python
The len()
function gives us the number of elements in an object. The following code example shows us how we can use the len(x)
method to get the shape of a list in Python.
lista = [[1,2,3],[4,5,6]]
arow = len(lista)
acol = len(lista[0])
print("Rows : " + str(arow))
print("Columns : " + str(acol))
Output:
Rows : 2
Columns : 3
In the above code, we first get the number of rows in lista
using len(lista)
and then get the number of columns in lista
using len(lista[0])
.
Get the Shape of a List With the numpy.shape()
Method in Python
If we want our code to work with any multidimensional lists, we have to use the numpy.shape()
method. The numpy.shape()
method gives us the number of elements in each dimension of an array. numpy.shape()
returns a tuple that contains the number of elements in each dimension of an array. The NumPy
package is originally designed to be used with arrays but could also work with lists.
NumPy
is an external package and does not come preinstalled with Python. We need to install it before using it. The command to install the NumPy
package is given below.
pip install numpy
The following code example shows how we can get the shape of a list using the numpy.shape()
method.
import numpy as np
lista = [1,2,3,4,5]
listb = [[1,2,3],[4,5,6]]
print("Shape of lista is : "+str(np.shape(lista)))
print("Shape of listb is : "+str(np.shape(listb)))
Output:
Shape of lista is : (5,)
Shape of listb is : (2, 3)
As it is clear from the above example, the numpy.shape()
method can be used with lists of any dimensions.
Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.
LinkedIn