Saturday, May 16, 2009

How to sort a Python tuple

Python tuple is immutable. Therefore, it cannot be changed.

To sort a Python tuple, we can create a new list using sorted() method.

If we still need it as a tuple, just apply tuple() to the new list.
>>> z = (1, 4, 3, 7, 2, 12, -3, 3)
>>> sorted_z = tuple(sorted(z))
>>> sorted_z
(-3, 1, 2, 3, 3, 4, 7, 12)