Ways to shuffle a Tuple in Python
Last Updated :
29 Aug, 2020
Shuffling numbers can sometimes prove to be a great help while programming practices. This process can be directly implemented on the data structures which are mutable like lists, but as we know that the tuples are immutable so it cannot be shuffled directly. If you’ll try to do so as done in the below code then an error will be raised. Let’s see the below example.
Python3
import random
t = ( 1 , 2 , 3 , 4 , 5 )
random.shuffle(t)
|
Output:
TypeError: 'tuple' object does not support item assignment
Then how to proceed? So there are two ways to shuffle tuple, and they are mentioned below:
Method #1: Typecasting
This a simple method to do shuffling in tuples. You can typecast the tuples to a list and then perform shuffling operations done on the list and then typecast that list back to the tuple. One way is to use random.shuffle().
Python3
import random
tup = ( 1 , 2 , 3 , 4 , 5 )
print ( "The original tuple is : " + str (tup))
l = list (tup)
random.shuffle(l)
tup = tuple (l)
print ( "The shuffled tuple is : " + str (tup))
|
Output:
The original tuple is: (1, 2, 3, 4, 5)
The shuffled tuple is: (2, 3, 4, 1, 5)
Method #2: Using random.sample()
random.sample() creates a new object and even if a tuple is passed as a first argument it returns a list, so as a last step it is mandatory to convert the list back to the tuple to get a shuffled tuple as an output.
Python3
import random
tup = ( 1 , 2 , 3 , 4 , 5 )
print ( "The original tuple is : " + str (tup))
tup = tuple (random.sample(t, len (t)))
print ( "The shuffled tuple is : " + str (tup))
|
Output:
The original tuple is: (1, 2, 3, 4, 5)
The shuffled tuple is: (1, 5, 3, 2, 4)
Share your thoughts in the comments
Please Login to comment...