How to reverse a tuple in Python: sorted() can reverse a tuple but returns a list

You can reverse a tuple using the Python slicing syntax.

t1 = ('A', 'B', 'C')
t2 = (7,)
t3 = ()

r1 = t1[::-1]
r2 = t2[::-1]
r3 = t3[::-1]

print(r1)  # ('C', 'B', 'A')
print(r2)  # (7,)
print(r3)  # ()

A tuple containing only one element is reversed to itself and of course an empty tuple remains itself. The expression [::-1] is one of the most useful slicing syntax.

Slicing syntax

The slicing syntax has three values (start, stop and step) and two semicolons as delimiters. The slicing syntax literally slices Python lists or tuples in some conditions. The start and stop can be omitted like above code.

In the example, because the start and stop is omitted and the absolute value of the step is 1, the sliced tuple ranges all the elements of the original tuple. The negative step means the reversed order. This syntax [::-1] is also used by reversing a list.

sorted() can sort a tuple but...

Why does this page introduce the slicing syntax instead of a common built in function sorted()? For, it doesn't return a tuple. It's interesting that sorted() sorts a tuple and returns a list.

a = (1, 2, 3, 4)

b = sorted(a, reverse=True)

print(b)  # [4, 3, 2, 1]
print(type(b))  # <class 'list'>

If you want a reversed tuple, you need to convert the result list to a new tuple.


Powered by Markdown