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.
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().
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.
The original tuple is: (1, 2, 3, 4, 5) The shuffled tuple is: (1, 5, 3, 2, 4)
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.