This error occurs if you try to call the
sort() method on an integer as if it were a list. You can solve this error by ensuring you do not assign an integer to a variable name for an existing list that you want to sort.
my_int = 14 my_list = [17, 222, 23, 14, 1, 45, 120] print(my_list.sort())
This tutorial will go through the error in detail and how to solve it with code examples.
AttributeError: ‘int’ object has no attribute ‘sort’
AttributeError occurs in a Python program when we try to access an attribute (method or property) that does not exist for a particular object.
sort() is a list method, which sorts the specified list in ascending order by default.
Let’s look at an example of trying to sort an integer. First, we will define a list of integers.
num = [2, 3, 12, 4, 10, 4, 27]
Next, we will use the
max() function to get the largest integer in the list and assign it to the variable name
num = max(num) print(num)
Then, we will attempt to sort the list of integers in ascending order and print the result to the console.
Let’s run the code code to see what happens:
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) Input In , in <cell line: 1>() ----> 1 num.sort() 2 print(num) AttributeError: 'int' object has no attribute 'sort'
The error occurs because we named the integer returned by the
num, which overrides the list with the same name. We can check the type of an object using the built-in
We can see that the
num variable stores an
int object, not a
We can solve the error by deleting the
int object with the name
num using the
del keyword and redefining the list with a unique name that we will not override.
del num num_list = [2, 3, 12, 4, 10, 4, 27] max_num = max(num_list) print(max_num) num_list.sort() print(num_list)
We also named the integer returned by the
max_num, which is different from the name of the list.
We can safely sort the list and print the result to the console.
[2, 3, 4, 4, 10, 12, 27]
Congratulations on reading to the end of this tutorial!
For further reading on AttributeErrors, go to the article:
- Python AttributeError: ‘list’ object has no attribute ‘split’
- How to Solve Python AttributeError: ‘int’ object has no attribute ‘split’
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!