Python - How To Get List Shape in Python

ID : 302

viewed : 52

Tags : PythonPython List

vote vote

98

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 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 . 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 is originally designed to be used with arrays but could also work with lists.

NumPy is an external package and does not come pre-installed 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.

  • Related HOW TO?