+1 vote
in Programming Languages by (17.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

0 votes
by (30.2k points)

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.


>>> 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')