Swap values in a tuple/list inside a list in python?

You can use reversed like this:

tuple(reversed((1, 2)) == (2, 1)

To apply it to a list, you can use map or a list/generator comprehension:

map(tuple, map(reversed, tuples))     # map
[tuple(reversed(x)) for x in tuples]  # list comprehension
(tuple(reversed(x)) for x in tuples)  # generator comprehension

If you're interested primarily in runtime speed, I can only recommend that you profile the various approaches and pick the fastest.


A fancy way:

[t[::-1] for t in mylist]

You could use map:

map (lambda t: (t[1], t[0]), mylist)

Or list comprehension:

[(t[1], t[0]) for t in mylist]

List comprehensions are preferred and supposedly much faster than map when lambda is needed, however note that list comprehension has a strict evaluation, that is it will be evaluated as soon as it gets bound to variable, if you're worried about memory consumption use a generator instead:

g = ((t[1], t[0]) for t in mylist)
#call when you need a value
g.next()

There are some more details here: Python List Comprehension Vs. Map