+4 votes
in Programming Languages by (77.2k points)

I am sorting a tuple using sort(),  but it gives an error. How can I fix the error and sort the tuple?

>>> t.sort()

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

AttributeError: 'tuple' object has no attribute 'sort'

1 Answer

+2 votes
by (354k points)
selected by
 
Best answer

If you want to use sort(), you need to convert the tuple to a list; then sort the list. Once you have sorted the list, you can convert the sorted list to a tuple.

You can also use the sorted() function to sort a tuple without converting it to a list. The sorted() function will convert the tuple to a list.

Example:

>>> t = ('cc', 'aa', 'dd', 'bb')
>>> t1=list(t)
>>> t1.sort()
>>> tuple(t1)
('aa', 'bb', 'cc', 'dd')

>>> t
('cc', 'aa', 'dd', 'bb')
>>> sorted(t)
['aa', 'bb', 'cc', 'dd']
>>> tuple(sorted(t))
('aa', 'bb', 'cc', 'dd')


...