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.
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.
There are two idiomatic ways to do this:
or
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 toi.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, andreversed
when the tuple is large, but performance in python is often surprising so measure it!Similar to the way you would reverse a list, i.e. s[::-1]
and
You can use the
reversed
builtin function.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.