How to create a tuple of random elements in Python

In this tutorial, we will see how to create a tuple of random elements in Python.

A Tuple in Python is a collection of immutable elements enclosed in parentheses or in other words a collection of sequenced and unchangeable elements that are enclosed in round brackets.

Create a Tuple of random elements in Python

Firstly, import random to use numpy.random.randint function to generate random elements from a specified range of elements from starting_int to end_int range as shown in the example below.

 

There are further two ways to use the random function to generate random elements :

  • without size in a parameter.

 

For instance, add parameters to the function and print variable X as shown in the example below.

 

INPUT:

import numpy as np
import random

X=np.random.randint(10,20)
print(X)

 

OUTPUT:

12

 

After that, an element is generated. Meanwhile, integer values just can’t directly be used to generate a tuple so to create a tuple, the next step is to change the integer values to an array type as tuple can be generated through an array type.

 

INPUT:

z=np.array([X])

 

After that, create a tuple and print it and use type function to check the type of the element.

 

INPUT:

Tuple_1= tuple(z)
print(Tuple_1)
print(type(Tuple_1))

 

OUTPUT:

(12,)
<class 'tuple'>

 

  • with size in a parameter.

 

Above all, the basic difference is it doesn’t need an array function instead it uses size in a parameter so similarly add parameters with the size too, create a tuple, print it and check the type.

 

INPUT:

import numpy as np
import random 

X=np.random.randint(10,20,size=10)
print(X)

Tuple_1=tuple(X)
print(Tuple_1)
print(type(Tuple_1))

 

OUTPUT:

[15 15 11 10 16 17 15 12 14 10]
(15, 15, 11, 10, 16, 17, 15, 12, 14, 10)
<class 'tuple'>

And boom! here is a Tuple of random elements. I hope this was helpful for all you coders. Happy Coding to ya all!

Also read:

Leave a Reply

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