RE: Error: ‘list’ object has no attribute ‘shape’ in Python

I am trying to use the 'shape' attribute on a list object in Python. It gives me the error: 'list' object has no attribute 'shape'. I want to find the dimensions of my list. How should I proceed?

Add Comment
1 Answers
The 'shape' attribute is not a native attribute of list objects in Python. You are likely getting this error because 'shape' is an attribute commonly used with NumPy arrays, not with Python lists. If your list is a one-dimensional Python list, you can use the built-in len() function to get the number of elements in the list: len(your_list) If your list involves more dimensions, you can use nested len() functions for each level: len(your_list) # number of rows (if you consider outer list as rows) len(your_list[0]) # number of columns, considering you have uniform nested lists If your array is not uniform (i.e., it has varying lengths of sublists), you'll need to account for this with more complex code. For a multidimensional 'shape' functionality similar to NumPy arrays, consider converting your list into a NumPy array. NumPy's 'np.array()' function comes handy for this: import numpy as np numpy_array = np.array(your_list) print(numpy_array.shape) This will provide you a tuple with number of dimensions in each level, similar to using 'shape' attribute in higher-dimensional data handling. But remember, lists and numpy arrays are different in many other aspects, so make sure numpy array suits your requirements before this conversion.
Answered on July 11, 2023.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.