How to reverse tuples in a list?

Simon Forman rogue_pedro at yahoo.com
Tue Aug 8 20:13:40 EDT 2006


Noah wrote:
> I have a list of tuples
>     [('a', 1.0), ('b', 2.0), ('c', 3.0)]
> I want to reverse the order of the elements inside the tuples.
>     [(1.0,'a'), (2.0, 'b'), (3.0, 'c')]
>
> I know I could do this long-form:
>     q = []
>     y = [('a', 1.0), ('b', 2.0), ('c', 3.0)]
>     for i in y:
>         t=list(t)
>         t.reverse()
>         q.append(tuple(t))
>     y = q
>
> But it seems like there should be a clever way to do this with
> a list comprehensions. Problem is I can't see how to apply
> reverse() to  each tuple  in the list because reverse() a
> list method (not a tuple method) and because it operates
> in-place (does not return a value). This kind of wrecks doing
> it in a list comprehension. What I'd like to say is something like
> this:
>     y = [t.reverse() for t in y]
> Even if reverse worked on tuples, it wouldn't work inside a
> list comprehension.
>
> Yours,
> Noah

If your tuples are all two items, you can do it like this:

y = [(b, a) for a, b in y]

if not, then:

y = [tuple(reversed(t)) for t in y]

:-D

Peace,
~Simon




More information about the Python-list mailing list