Skip to content
Related Articles

Related Articles

Improve Article
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
  
# Initializing tuple
t = (1,2,3,4,5)
  
# Trying to shuffle using random.shuffle
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




# Python3 code to demonstrate  
# shuffle a tuple  
# using random.shuffle() 
import random 
  
# initializing tuple
tup = (1,2,3,4,5)
  
# Printing original tuple
print("The original tuple is : " + str(tup))
  
# Conversion to list
l = list(tup)
  
# using random.shuffle() 
# to shuffle a list
random.shuffle(l)
  
# Converting back to tuple
tup = tuple(l)
  
# Printing shuffled tuple
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




# Python3 code to demonstrate  
# shuffle a tuple  
# using random.sample() 
import random 
  
# initializing tuple
tup = (1,2,3,4,5)
  
# Printing original tuple
print("The original tuple is : " + str(tup))
  
# Using random.sample(), passing the tuple and 
# the length of the datastructure as arguments
# and converting it back to tuple.
tup = tuple(random.sample(t, len(t)))
  
# Printing shuffled tuple
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)

 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. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :