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 = 6 print (tuple)
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)
1 2 3 4 5
(5, 3, 2, 1, 4)
- imports the random module
- Get the user input
- Converts the tuple into list.
- shuffle method is called from random module in order to shuffle the list.
- The shuffled list is converted back to tuple.
- 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.