user13435420
user13435420

Reputation: 19

Reversing the order of a list of lists or list of tuples

I have a list of tuples:

ls = [('hello', 'there'), ('whats', 'up'), ('no', 'idea')]

I want to reverse the order of each tuple in the list.

ls = [('there', 'hello'), ('up', 'whats'), ('idea', 'no')]

I know tuples are immutable so I'll need to create new tuples. I'm not really sure what's the best way to go about it. I could change the list of tuples into a list of lists, but I'm thinking there might be a more efficient way to go about this.

Upvotes: 1

Views: 135

Answers (2)

Red
Red

Reputation: 27567

Input:

ls = [('hello', 'there'), ('whats', 'up'), ('no', 'idea')]

ls = [(f,s) for s,f in ls]
print(ls)

Output:

[('there', 'hello'), ('up', 'whats'), ('idea', 'no')]

Upvotes: 0

user2390182
user2390182

Reputation: 73470

Just use a list comprehension along the following lines:

ls = [tpl[::-1] for tpl in ls]

This uses the typical [::-1] slice pattern to reverse the tuples.

Also note that the list itself is not immutable, so if you needed to mutate the original list, and not just rebind the ls variable, you could use slice assignment:

ls[:] = [tpl[::-1] for tpl in ls]

This is the short-hand equivalent of a loop-based approach à la:

for i, tpl in enumerate(ls):
    ls[i] = tpl[::-1]

Upvotes: 6

Related Questions