How to reverse tuples in Python?

PythonLoopsIterationTuples

Python Problem Overview


> Possible Duplicate:
> Traverse a list in reverse order in Python

Is this possible? Doesn't have to be in place, just looking for a way to reverse a tuple so I can iterate on it backwards.

Python Solutions


Solution 1 - Python

There are two idiomatic ways to do this:

reversed(x)  # returns an iterator

or

x[::-1]  # returns a new tuple

Since tuples are immutable, there is no way to reverse a tuple in-place.


Edit: Building on @lvc's comment, the iterator returned by reversed would be equivalent to

def myreversed(seq):
    for i in range(len(x) - 1, -1, -1):
        yield seq[i]

i.e. it relies on the sequence having a known length to avoid having to actually reverse the tuple.

As to which is more efficient, i'd suspect it'd be the seq[::-1] if you are using all of it and the tuple is small, and reversed when the tuple is large, but performance in python is often surprising so measure it!

Solution 2 - Python

You can use the reversed builtin function.

>>> x = (1, 2, 3, 4)
>>> x = tuple(reversed(x))
>>> x
(4, 3, 2, 1)

If you just want to iterate over the tuple, you can just use the iterator returned by reversed directly without converting it into a tuple again.

>>> for k in reversed(x):
...     print(k)
... 
4 3 2 1

Solution 3 - Python

Similar to the way you would reverse a list, i.e. s[::-1]

In [20]: s = (1, 2, 3)

In [21]: s[::-1]
Out[21]: (3, 2, 1)

and

In [24]: for i in s[::-1]:
   ....:     print i
   ....:
3
2
1

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJoan VengeView Question on Stackoverflow
Solution 1 - PythontobyodaviesView Answer on Stackoverflow
Solution 2 - PythonPraveen GollakotaView Answer on Stackoverflow
Solution 3 - PythonLevonView Answer on Stackoverflow