Select Page

How to Solve Python AttributeError: ‘list’ object has no attribute ‘dtype’

by | Programming, Python, Tips

In Python, a list is a container object that stores elements in sequential order. A similar container object is the ndarray in the NumPy library. Every ndarray has an associated data type (dtype) which contains information about the array.

However, lists do not have the dtype object. If you try to get the dtype object from a list, you will raise the “AttributeError: ‘list’ object has no attribute ‘dtype’”.

To solve this error, ensure you convert the list to a ndarray using the numpy.array() method.

This tutorial will go into detail on the error definition. We will go through an example that causes the error and how to solve it.


AttributeError: ‘list’ object has no attribute ‘dtype’

AttributeError occurs in a Python program when we try to access an attribute (method or property) that does not exist for a particular object. The part “‘list’ object has no attribute ‘dtype’” tells us that the list object we are handling does not have the dtype attribute. We will raise this error when trying to create an instance of the dtype class for a list object.

NumPy dtype

dtype is a data type object and is an instance of the numpy.dtype class. The object describes the following aspects of the data:

  1. Type of the data (int, float etc.)
  2. Size of the data in bytes
  3. Byte order of the data (little-endian or big-endian)
  4. If the data type is structured data type, which are arbitrarily complex dtypes that can include other arrays and dtypes
  5. If the data type is a sub-array, its shape and data type

Let’s look at an example of getting the dtype of a numpy array:

import numpy as np

x = np.array([2, 4, 6])

print(f"dtype of array is: {x.dtype}")
dtype of array is: int64

Let’s look at what happens when we try to get the dtype of an ordinary Python list:

import numpy as np

x = [2, 4, 6]

print(f"dtype of list is: {x.dtype}")
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-2-928109bc0f67> in <module>
      1 x = [2, 4, 6]
      2 
----> 3 print(f"dtype of list is: {x.dtype}")

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

The Python interpreter raises the error because dtype is not an attribute of ordinary Python lists. You may encounter this error if you use a function that requires ndarrays. Let’s look at an in-depth example in the next section.

Example

In this example, we will create a structured array, which is an array that contains different types of data. We can access structured arrays with the help of fields.

We can think of a field as an identifier to the dtype object

Our structured array will contain the names of pizzas and their prices.

import numpy as np
 
# A structured data type containing a 16-character string (in field ‘pizza’) 
# and a sub-array of one 64-bit floating-point number (in field ‘price’):
 
dt = np.dtype([('pizza', np.unicode_, 16), ('price', np.float64, (1,))])

# Data type of object with field grades
print(dt['pizza'])
 
# Data type of object with field name 
print(dt['price'])
<U16
('<f8', (1,))

Next, we will define a nested list with the names and prices of three pizzas.

Let’s try to set the data type of the nested list to the structured data type defined above:

x = [('margherita', 7.99), ('pepperoni',9.99), ('four cheeses', 10.99)]
x.dtype(dt)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-8-84cd41772883> in <module>
      1 x = [('margherita', 7.99), ('pepperoni',9.99), ('four cheeses', 10.99)]
----> 2 x.dtype(dt)

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

We get the AttributeError because the Python interpreter expects a NumPy ndarray, but instead, we provided a built-in Python list. The list object does not have dtype as an attribute.

Solution

To solve this error, we need to convert the Python list to a ndarray using the numpy.array() method. We can also pass the structure dtype object as a parameter with the key “dtype” when we convert the list. Let’s look at the revised code

x = np.array([('margherita', 7.99), ('pepperoni',9.99), ('four cheeses', 10.99)], dtype=dt)

Now we can access the information in the structured array using the fields:

print(f"The available pizzas are {x['pizza']}")
print(f"The price of the pepperoni pizza is: {x[1]['price']}")
The available pizzas are ['margherita' 'pepperoni' 'four cheeses']
The price of the pepperoni pizza is: [9.99]

Summary

Congratulations on reading to the end of this tutorial! The error “AttributeError: ‘list’ object has no attribute ‘dtype’” occurs when you try to access or set the dtype object of a list as if it were a NumPy ndarray

To access or set the dtype object, you must convert the list to a NumPy ndarray using the numpy.array() method. You can pass the dtype you want as a parameter when defining the ndarray.

Generally, check the type of object you are using is a ndarray before calling setting the dtype or attempting to use any methods or classes belonging to the NumPy library.

For further reading on AttributeErrors involving the list object, go to the articles:

To learn more about Python for data science and machine learning, go to the online courses page on Python for the most comprehensive courses available.

Have fun and happy researching!