Reputation: 47
I'm trying to reverse a tuple in different ways. Can i change the order in way (bond,james,number). I know how to change it if there are only 2 elements in tuple but how to do it when I have 3 and more? I got (number,bond,james) but how to do it in different ways, not just reversing. My code:
def change(lst):
list2 = [t[::-1] for t in lst]
list2.reverse()
return list2
print(change([("James", "Bond", "300184"),("Harry", "Prince", "111000")]))
Upvotes: 2
Views: 344
Reputation: 34
You can get all possible combinations of a tuple using itertools permutation:
from itertools import permutations
list1 = [("James", "Bond", "300184"), ("Harry", "Prince", "111000")]
for tup in list1:
possible_permutations = permutations(tup)
print(tuple(possible_permutations))
Output:
(('James', 'Bond', '300184'), ('James', '300184', 'Bond'), ('Bond', 'James', '300184'), ('Bond', '300184', 'James'), ('300184', 'James', 'Bond'), ('300184', 'Bond', 'James'))
(('Harry', 'Prince', '111000'), ('Harry', '111000', 'Prince'), ('Prince', 'Harry', '111000'), ('Prince', '111000', 'Harry'), ('111000', 'Harry', 'Prince'), ('111000', 'Prince', 'Harry'))
Upvotes: 0
Reputation: 20669
If you want to reverse the first two elements we can leverage on tuple unpacking in for loop.
lst = [("James", "Bond", "300184"),("Harry", "Prince", "111000")]
out = [(sec, fir, *rem) for fir, sec, *rem in lst]
print(out)
# [('Bond', 'James', '300184'), ('Prince', 'Harry', '111000')]
This solution would reverse each tuple in list as below:
(a, b, c...z) --> (b, a, c...z)
c...z
can be 0 or more elements.Upvotes: 1