[SOLVED] changing position of elements within a tuple in python


This Content is from Stack Overflow. Question asked by zaakm

Is there an operation which can change position of elements within a tuple, like for instance I have a tuple (‘a’, ‘b’) and I want to change it to (‘b’, ‘a’)

Yes it can be done by writing into a new tuple but I was wondering if there is an operation which could do it for me.


tuples are immutable objects in python, so you can’t do this without creating a new tuple. bit of an explanation here: python tuple is immutable – so why can I add elements to it

one way you could do this (if it will only ever be two elements in the tuple) is:

my_tuple = my_tuple[1], my_tuple[0]

This Question was asked in StackOverflow by zaakm and Answered by Luke Scales It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?