AttributeError: 'list' object has no attribute 'shape'

avatar

Borislav Hadzhiev

Wed Apr 20 20222 min read

banner

Photo by Lê Tân

AttributeError: 'list' object has no attribute 'shape' #

The Python "AttributeError: 'list' object has no attribute 'shape'" occurs when we try to access the shape attribute on a list. To solve the error, pass the list to the numpy.array() method to create a numpy array before accessing the shape attribute.

attributeerror list object has no attribute shape

Here is an example of how the error occurs.

main.py
my_list = [1, 2, 3] # # ⛔️ AttributeError: 'list' object has no attribute 'shape' print(my_list.shape)

To solve the error, pass the list to the np.array() method to create a numpy array.

main.py
import numpy as np np_array = np.array([1, 2, 3]) print(np_array.shape) # 👉️ (3,)

The numpy.array method takes an array-like object as an argument and creates an array.

You might also use the numpy.asarray method to convert a list into a numpy array before accessing the shape attribute.

main.py
import numpy as np np_array = np.asarray([1, 2, 3]) print(np_array.shape) # 👉️ (3,)

Alternatively, you can pass the list directly to the numpy.shape method.

main.py
import numpy as np array_shape = np.shape([1, 2, 3]) print(array_shape) # 👉️ (3,) print(np.shape([[1, 2]])) # 👉️ (1, 2) print(np.shape([0])) # 👉️ (1,)

The numpy.shape method takes an array-like object as an argument and returns the shape of the array.

The elements of the shape tuple give the lengths of the corresponding array dimensions.

If you need to get the length of a list, use the len() function.

main.py
my_list = [[1, 2, 3], [4, 5, 6]] # 👇️ get length of entire list print(len(my_list)) # 👉️ 2 # 👇️ get length of list item at index 0 print(len(my_list[0])) # 👉️ 3

The len() function returns the length (the number of items) of an object.

The argument the function takes may be a sequence (a string, tuple, list, range or bytes) or a collection (a dictionary, set, or frozen set).

You can view all the attributes an object has by using the dir() function.

main.py
my_list = ['a', 'b', 'c'] # 👉️ [... 'append', 'clear', 'copy', 'count', 'extend', 'index', # 'insert', 'pop', 'remove', 'reverse', 'sort' ...] print(dir(my_list))

If you pass a class to the dir() function, it returns a list of names of the classes' attributes, and recursively of the attributes of its bases.

If you try to access any attribute that is not in this list, you would get the "AttributeError: list object has no attribute" error.

Use the search field on my Home Page to filter through my more than 1,000 articles.