How to reverse tuples in a list?
Noah
noah at noah.org
Tue Aug 8 20:01:11 EDT 2006
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
More information about the Python-list
mailing list