Home > other >  changing position of elements within a tuple in python
changing position of elements within a tuple in python

Time:09-19

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.

CodePudding user response:

No, tuples are immutable. Once it's created, it cannot be changed.

If all you want is an operation to write the changed order into a new tuple, you can use indexing. For two elements that looks like this:

mytuple = ('a', 'b')
mytuple = mytuple[1], mytuple[0]

The result is still a new tuple but stored at the same name ("mytuple").

CodePudding user response:

Well since tuples are immutable, so once its created you won't be able to change it directly. To create the tuple you want, this should work.

tuple_1 = (1, 2)
tuple_2 = tuple_1[::-1]

The answer will be reversed, in a tuple, but not the same tuple.

CodePudding user response:

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]
  • Related