Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reverse tuples in Python? [duplicate]

Possible Duplicate:
Traverse a list in reverse order in Python

Is this possible? Doesn't have to be in place, just looking for a way to reverse a tuple so I can iterate on it backwards.

like image 756
Joan Venge Avatar asked Apr 18 '12 02:04

Joan Venge


People also ask

Is it possible to reverse tuple in Python?

Since tuples are immutable, there is no way to reverse a tuple in-place.

How do I remove duplicates from a tuple in Python?

Method #1 : Using set() + tuple() This is the most straight forward way to remove duplicates. In this, we convert the tuple to a set, removing duplicates and then converting it back again using tuple().

How do you reverse a tuple list in Python?

In Python, you can reverse the items of lists ( list ) with using reverse() , reversed() , and slicing. If you want to reverse strings ( str ) and tuples ( tuple ), use reversed() or slice.

Can tuples in Python have duplicates?

31.2 Python Collection TypesTuples allow duplicate members and are indexed. Lists Lists hold a collection of objects that are ordered and mutable (changeable), they are indexed and allow duplicate members.


2 Answers

There are two idiomatic ways to do this:

reversed(x)  # returns an iterator 

or

x[::-1]  # returns a new tuple 

Since tuples are immutable, there is no way to reverse a tuple in-place.


Edit: Building on @lvc's comment, the iterator returned by reversed would be equivalent to

def myreversed(seq):     for i in range(len(x) - 1, -1, -1):         yield seq[i] 

i.e. it relies on the sequence having a known length to avoid having to actually reverse the tuple.

As to which is more efficient, i'd suspect it'd be the seq[::-1] if you are using all of it and the tuple is small, and reversed when the tuple is large, but performance in python is often surprising so measure it!

like image 134
tobyodavies Avatar answered Sep 21 '22 21:09

tobyodavies


You can use the reversed builtin function.

>>> x = (1, 2, 3, 4) >>> x = tuple(reversed(x)) >>> x (4, 3, 2, 1) 

If you just want to iterate over the tuple, you can just use the iterator returned by reversed directly without converting it into a tuple again.

>>> for k in reversed(x): ...     print(k) ...  4 3 2 1 
like image 40
Praveen Gollakota Avatar answered Sep 20 '22 21:09

Praveen Gollakota