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

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Check out my new book

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

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

attributeerror list object has no attribute astype

Here is an example of how the error occurs.

main.py
my_list = [1, 2, 2.5, 3.6] # ⛔️ AttributeError: 'list' object has no attribute 'astype' result = my_list.astype(int)

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

main.py
import numpy as np my_list = [1, 2, 2.5, 3.6] np_array = np.array(my_list, dtype=np.int32) print(np_array) # 👉️ [1 2 2 3]

The dtype keyword argument can be used to set the data type of the array's elements.

You can use the astype method on a numpy array to copy the array and cast it to a specified type.

main.py
import numpy as np my_list = [1, 2, 2.5, 3.6] np_array = np.array(my_list, dtype=np.int32) print(np_array) # 👉️ [1 2 2 3] result = np_array.astype(np.float32) print(result) # 👉️ [1. 2. 2. 3.]

The only parameter we passed to the astype method is the data type to which the array is cast.

main.py
import numpy as np my_list = [1, 2, 2.5, 3.6] np_array = np.array(my_list) result = np_array.astype(int) print(result) # 👉️ [1 2 2 3]

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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.