Reputation: 29074
I have a tuple and would like to reverse it in Python.
The tuple looks like this : (2, (4, (1, (10, None))))
.
I tried reversing in Python by:
a = (2, (4, (1, (10, None))))
b = reversed(a)
It returns me this:
<reversed object at 0x02C73270>
How do I get the reverse of a
? Or must I write a function to do this?
The result should look like this:
((((None, 10), 1), 4), 2)
Upvotes: 1
Views: 816
Reputation: 82899
Try this deep-reverse function:
def deep_reverse(t):
return tuple(deep_reverse(x) if isinstance(x, tuple) else x
for x in reversed(t))
This will handle arbitrarily nested tuples, not just two-tuples.
Upvotes: 3
Reputation: 362786
def my_reverser(x):
try:
x_ = x[::-1]
except TypeError:
return x
else:
return x if len(x) == 1 else tuple(my_reverser(e) for e in x_)
Upvotes: 3
Reputation: 59436
It does not make sense to do this with reversed
, sorry. But a simple recursive function would return what you want:
def reversedLinkedTuple(t):
if t is None:
return t
a, b = t
return reversedLinkedTuple(b), a
reversed
is usable only on reversible iterable objects like lists, tuples and the like. What you are using (a linked list) isn't iterable in the sense of the Python built-in iter
.
You could write a wrapping class for your linked list which implements this and then offers a reverse iterator, but I think that would be overkill and would not really suit your needs.
Upvotes: 1
Reputation: 20339
As explained in the documentation, the reversed
function returns an iterator (hence the <reversed at ...>
). If you want to get a list or a tuple out of it, just use list(reversed(...))
or tuple(reversed(...))
.
However, it's only part of our problem: you'll be reversing the initial object (2, (...))
as (...,2)
, while the ...
stays the same. You have to implement a recursive reverse: if one element of your input tuple is an iterable, you need to reverse it to.
Upvotes: 2