. Advertisement .
..3..
. Advertisement .
..4..
Guido van Rossum created Python as a powerful, elevated, object-oriented technology platform. It’s easy to learn and is rapidly becoming one of the greatest beginner computer languages.
We’ll learn How to get List Shape in Python in this guide. Thus, without further hesitation, let us gain more knowledge on this.
How to get list shape in python
The shape of one list would be determined using the built-in function len() and the NumPy module. The shape of this list would ordinarily return the objects in a list. The list’s shape can be calculated using len() and NumPy array shapes. Numpy does have an attribute called np.shape that can be used to determine the shape of the list or tuple. For the recursive list, we can also compute a shape. Then, in this guidance, we’ll look at different methods for getting List Shape in Python. You must use one of the two commonly used methods highlighted below to overcome this matter.
Method 1: Use “len()”
We can get list shape in Python by using len()
. The len() function tells us how many elements are included in an object. The len(x)
method can be used in Python to determine the form of a list, as demonstrated by the following code sample.
list1 = [[3,5,6],[4,5,6],[5,6,6]]
arow = len(list1)
acol = len(list1[0])
print("Rows : " + str(arow))
print("Columns : " + str(acol))
Output
Rows : 3
Columns : 3
Method 2: Use “numpy.shape()”
Using the numpy.shape() method is required for any multidimensional lists if we want to run our code with them. We can find out how many elements are present in each dimension of an array by using the numpy.shape()
method. A tuple containing the number of elements in each dimension of an array is the result of the numpy.shape()
function. The NumPy
library not only can be used with arrays, but also it can be used with lists.
Since NumP
y is an external package, Python does not already have it installed. Before using it, we must install it. Below is the command you run in order to install the NumPy
package.
pip install numpy
The numpy.shape()
method is used in the following code example to get list shape in Python. Let’s consider it.
import numpy as np
list1 = [1,2,3]
list2 = [[1,2],[3,4]]
print("Shape of list1 is : "+str(np.shape(list1)))
print("Shape of list2 is : "+str(np.shape(list2)))
Output
Shape of lista is : (3,)
Shape of listb is : (2, 2)
Conclusion
Python is dynamically typed, and shared memory is handled automatically. Python has amazing high database systems and a straightforward yet effective method for object-oriented coding. At last, the two methods introduced are straightforward solutions to the above major question: “How to get List Shape in python“. Please leave your new ideas in the comment box if you have some additional concerns. We hope all Python participants have a gainful day with the platform.
Read more
Let’s read this useful article to get more knowledge about Python:
Leave a comment