Borislav Hadzhiev
Wed Apr 20 2022·2 min read
Photo by Brooke Cagle
The Python "AttributeError: 'tuple' object has no attribute 'sort'" occurs
when we try to call the sort()
method on a tuple instead of a list. To solve
the error, use a list instead of a tuple, e.g. ['c', 'b', 'a'].sort()
, because
tuples are immutable.
Here is an example of how the error occurs.
my_list = ('c', 'b', 'a') print(type(my_list)) # 👉️ <class 'tuple'> # ⛔️ AttributeError: 'tuple' object has no attribute 'sort' my_list.sort()
We used parenthesis to wrap the comma-separated elements, so we ended up creating a tuple object.
To solve the error, we have to use a list instead of a tuple.
my_list = ['c', 'b', 'a'] print(type(my_list)) # 👉️ <class 'list'> my_list.sort() print(my_list) # 👉️ ['a', 'b', 'c']
We wrapped the items in square brackets to create a list and we were able to
call the sort()
method to sort the list.
You can convert a tuple into a list by using the list()
constructor.
my_tuple = ('c', 'b', 'a') my_list = list(my_tuple) my_list.sort() print(my_list) # 👉️ ['a', 'b', 'c']
sort()
which change the object in place.Note that the sort()
method sorts the list in place, it doesn't return a new
sorted list.
In fact the sort()
method returns None
, so don't assign the result of
calling it to a variable.
If you need to mutate the sequence, you have to use a list
because tuples are
immutable.
There are only 2 methods that you will likely be using on tuple objects.
my_tuple = ('a', 'b', 'c', 'c') print(my_tuple.count('c')) # 👉️ 2 print(my_tuple.index('a')) # 👉️ 0
The count
method returns the number of occurrences of the value in the tuple
and the index
method returns the index of the value in the tuple.
You can view all the attributes an object has by using the dir()
function.
my_tuple = ('a', 'b', 'c', 'c') # 👇️ [... 'count', 'index' ...] print(dir(my_tuple))
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: tuple object has no attribute" error.