How to reverse tuples in a list?

Wildemar Wildenburger wildemar at freakmail.de
Wed Aug 9 10:24:43 EDT 2006


Noah wrote (among other things ;)):
> I have a list of tuples
> I want to reverse the order of the elements inside the tuples.
> 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.

This is a minor point, but I've got the impression you're not completely 
aware that tuples are immutable, and what that implies. I mean that 
t.reverse(), assuming the same semantics as the list method, is just not 
possible, as it would try to alter the tuple. This is not what tuples 
are for, so there.

Sorry if you knew this, just wanted to point out that there is a 
conscious difference between tuples and lists.
This is of course just a half-newbie crackin wise, so forgive me ;).

wildemar




More information about the Python-list mailing list