cᴏʟᴅsᴘᴇᴇᴅ cᴏʟᴅsᴘᴇᴇᴅ - 3 years ago 126
Python Question

How do I reverse tuples in a list of tuples using python?

Given a list of tuples:

l = [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')]

I'd like to find the quickest and simplest way to reverse each individual tuple in
, so that I get:

[('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)]

I'm sure there's a simple way to do this, but I'm not sure how. How can this be done?

P.S.: Let me know if a duplicate exists. I've searched and haven't found one.

Answer Source
l2 = [t[::-1] for t in l]

Use standard negative-step slicing t[::-1] to get the reverse of a tuple, and a list comprehension to get that for each tuple.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download