Borislav Hadzhiev
Last updated: Apr 20, 2022
Photo from Unsplash
The Python "AttributeError: 'list' object has no attribute 'reshape'" occurs
when we try to call the reshape()
method on a list. To solve the error, pass
the list to the numpy.array()
method to create a numpy array before calling
the reshape
method.
Here is an example of how the error occurs.
my_list = [0, 1, 2, 3, 4, 5] # ⛔️ AttributeError: 'list' object has no attribute 'reshape' reshaped = my_list.reshape((3, 2))
To solve the error, pass the list to the np.array()
method to create a numpy
array.
import numpy as np my_list = [0, 1, 2, 3, 4, 5] np_array = np.array(my_list) # [[0 1] # [2 3] # [4 5]] print(np_array.reshape((3, 2)))
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 calling the reshape
method.
import numpy as np my_list = [0, 1, 2, 3, 4, 5] np_array = np.asarray(my_list) # [[0 1] # [2 3] # [4 5]] print(np_array.reshape((3, 2)))
Alternatively, you can pass the list directly to the numpy.reshape method.
import numpy as np my_list = [0, 1, 2, 3, 4, 5] reshaped = np.reshape(my_list, (3, 2)) # [[0 1] # [2 3] # [4 5]] print(reshaped)
The numpy.reshape
method gives a new shape to an array without changing its
data.
import numpy as np my_list = [[0, 1, 2], [3, 4, 5]] reshaped = np.reshape(my_list, 6) print(reshaped) # [0 1 2 3 4 5]
The np.reshape
method takes an array like object as an argument and an int or
tuple of integers that represent the new shape.
The new shape should be compatible with the original shape.
If an integer is passed for the new shape argument, the result will be a 1-D array of that length.
If you need to get the length of a list, use the len()
function.
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.
You can view all the attributes an object has by using the dir()
function.
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.