How to shuffle elements of a tuple in Python

In this article, you can learn how to shuffle elements of a tuple in Python.

In Python, Tuple is used to store immutable objects. (i.e) the values cannot be changed.

Consider an example:

tuple = (1,2,3,4)
tuple[0] = 6
print (tuple)

Output:

Traceback (most recent call last):
  File "./prog.py", line 2, in <module>
TypeError: 'tuple' object does not support item assignment


In the above example, we tried to change the value of the first element but it cannot be done in a tuple in python. So it displayed an error.

Shuffle elements of a tuple in Python

As we mentioned in the above example Tuple in Python is immutable. So it cannot be shuffled directly.

Then how to do it?

We can typecast(change) it to a list(which is mutable) and then we can shuffle it and then typecast it back to tuple so that we can give the output as a tuple.

Now, how to shuffle a list?

We can shuffle a list in python by using an inbuilt method in python called shuffle from the module random.

Here is the code to shuffle a tuple:

import random 
tup = tuple(map(int,input().split()))
l = list(tup)
random.shuffle(l)
tup = tuple(l)
print (tup)

Sample Input:

1 2 3 4 5

Sample Output:

(5, 3, 2, 1, 4)

Code Explanation

Line

  1. imports the random module
  2. Get the user input
  3. Converts the tuple into list.
  4. shuffle method is called from random module in order to shuffle the list.
  5. The shuffled list is converted back to tuple.
  6. The shuffled tuple is printed.

There are many ways to shuffle a tuple. The above method is one of the easiest among them.

Hope you learned something new from this article.

Also read:

Leave a Reply

Your email address will not be published. Required fields are marked *