How to Generate Random Data in Python?

Posted in /  

How to Generate Random Data in Python?
vinaykhatri

Vinay Khatri
Last updated on November 23, 2024

    Knowing how to generate random data using Python can be very useful in many cases. You might need to generate random data for Email OPT in your web application, or you might be working with cryptography using Python, where you need to generate a random UUID. Similarly, there are many applications where you need to generate random data using Python.

    Generally, when it comes to generating random Data in Python, the first most library that comes to our mind is Python random module, but there are two other Standard modules in Python that can also be used to generate random data.

    In this Python tutorial, I will walk you through the python Different code snippets to Generate random data in Python. So open your best Python IDE or Text editor and follow along.

    Generate Random Numbers in Python

    There are two modules in Python that can be used to generate random numbers.

    1. Python random module
    2. Python secrets module

    For most of the cases, you will be using the Python random module to generate random numbers, but in case you wish to generate strong random numbers for the secret password, security token, and cryptography there, you should be using the Python secrets module.

    Generating random numbers with Python random module

    In a random module, you get two methods randint(start, end) and randrange(start, end, [steps]) to generate random numbers. The randint(start, end) will generate a random number greater than and equal to start and smaller than equal to end.

    The randrange(start, end, step) method will generate a random number between start and end with the interval of specified steps.

    import random
    
    #random number >=20, and <= 300
    print(random.randint(20, 300))
    
    #random number >=20, <300 and 20,30,...290
    print(random.randrange(20, 300, 10))

    Output

    162
    280

    Generating random numbers with the Python secrets module

    Using the Python secrets modules randbelow(n) method, we can generate a random number between o to n.

    import secrets
    
    #random number o to 99
    print(secrets.randbelow(100))

    Output

    78

    let's say you want to generate 4 digits random number for OTP in Python, for that you can use the Python randint() or randrange() method.

    import random
    
    #4 digit opt
    otp = random.randint(1000, 9999)
    
    print("Your Four Digit OTP is:", otp)

    Output

    Your Four Digit OTP is: 8901

    Choose Random Data From the Elements

    Let's say you have a Python list or any other sequence of elements, and you want to pick elements from the sequence. In that case, randomly, you can use the Python random or secrets module.

    Randomly chooses or pick elements from a Python List or sequence using the random module

    In the Python random module, we have two methods, namely choice() and choices() to pick random elements from the sequence. The choice(sequence) method picks a single random element from the sequence. and. The choices(sequence, k) pick k numbers of random elements from the sequence and return a list of k random picks.

    import random
    
    cards = ["ace", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "J", "K", "Q"]
    
    #pick one
    print(random.choice(cards))
    
    #pick 3 cards
    print(random.choices(cards, k =3))

    Output

    ten
    ['three', 'five', 'six']

    Randomly chooses or pick an element from a Python List or sequence using the secrets module

    In the secrets module, we also get the choice() method to randomly select one element from a Python list or sequence.

    import secrets
    cards = ["ace", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "J", "K", "Q"]
    
    #pick one
    print(secrets.choice(cards))

    Output

    seven

    Selecting random elements from a sequence can be very useful. We can use it in many applications, such as generating random long secure passwords from letters.

    Let's generate a 14-character-long random password in Python.

    #Python program to generate random passwords

    import string
    import secrets
    import random
    
    #"'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'"
    letters_digits = string.ascii_letters + string.digits
    
    #with random choices()
    passwords_random = "".join(random.choices(letters_digits, k=14) )
    print("14 characters long Randomly Generated Password:", passwords_random)
    
    #with secrets choice
    passwords_secrets = "".join([secrets.choice(letters_digits) for _ in range(14)])
    print("14 characters long Randomly Generated Password:", passwords_secrets)

    Output

    14 characters long Randomly Generated Password: X6WrjhOYUmmmbI
    14 characters long Randomly Generated Password: phx1opoYMj7QLg

    Generate Random Floating Points Numbers

    In the above example, we have only covered how to generate random Integer numbers. Let's say you want to generate random floating points or decimal points, or random numbers. Then what will we do?- the answer is simple we will use the random() method.

    The random module provides a random() method that generates a random floating-point number between 0.0 and 1.0 whenever you call it.

    import random
    
    print("Random Floating point number between 0.0 and 1.0 : ", random.random())

    Output Random Floating point number between 0.0 and 1.0: 0.3365084727758496 From the output, you can see that the random() function only returns a randomly generated floating-point number between 0.0 to 1.0. In many cases, it might do the work for you, but there is a high chance that you want to generate a big floating-point number with fixed decimal point numbers.

    To generate 1-digit floating point numbers, we will multiply the returned random() result by 10. To get a 2-digit floating-point number, will multiply the randomly generated floating-point number by 100 and so on. And to small the size of decimal points, we will round the numbers using the Python round function .

    import random
    
    #random floating number 
    num = random.random()*10000
    
    print("Random Floating Number", round(num, 2))

    Output

    Random Floating Number 6466.69

    The random module also provides another method uniform(start, end) that print a random floating number N , where start < = N <= end

    import random
    
    #random floating number 
    num = random.uniform(10, 10000)
    
    print("Random Floating Number", round(num, 2))

    Output

    Random Floating Number 3299.03

    Generate Random Data For Cryptography

    Although the Python random module provides many methods to generate random data, but it is not secure and reliable, and in most cases, you will see that it returns similar random data. And when we talk about cryptography where we require such logic or modules which can generate random and unique data for us.

    Luckily in Python, we have inbuilt Python standard os and secrets modules that can be used to generate random data in different formats. But in cryptography and security, you will be using the Python secrets module more than os , because it provides more methods to create random data.

    Generate Random bytes data for Cryptographic use using Python os module

    In Python os module, we get the urandom(N) function that generates random bytes data of N size that is suitable for cryptographic use. The bytes data returned by the urandom() function is Operating System specific.

    Example

    import os
    
    size= 20
    #random crypto-safe bytes data
    crypto_bytes = os.urandom(size)
    
    print("Random Bytes Data for Crypto: ", crypto_bytes)

    Output

    Random Bytes Data for Crypto: b'^ ]l\x8b\x1c\x83m\x15\xd53f\xb3e\x14X\xfa\xfa\x08\xe6'

    Generate Random bytes data for Cryptographic use using the Python secrets module

    The secrets module provides more methods to generate secure random token data in different data type formats. randbits(k) method returns a randomly generated integer with K random bits. token_bytes(N) method returns a randomly generated Nbytes long Byte string token.

    token_hex(N) method returns a randomly generated Nbytes long Hexadecimal string token. token_urlsafe(N) method returns a randomly generated Nbytes long Base64 encoded text.

    import secrets
    
    N= 18
    
    crypto_bytes = secrets.token_bytes(N)
    print("Random Secrets Token Bytes for Crypto:", crypto_bytes)
    
    crypto_rand_string = secrets.token_urlsafe(N)
    print("Random URL safe String for Crypto:", crypto_rand_string)
    
    crypto_hex = secrets.token_hex(N)
    print("Random Hexadecimal String for Crypto:", crypto_hex)
    
    crypto_int_bits = secrets.randbits(N)
    print("Random 18 bit Crypto Integer:",crypto_int_bits )

    Output

    Random Secrets Token Bytes for Crypto: b'm\xf9j\xd7\xf0J$,e\x01yz\x07V\xe4H\xa6"'
    Random URL safe String for Crypto: pSizKJUs39ywa74dLCGesPU_
    Random Hexadecimal String for Crypto: 96e5fb1e9db600e255ada174d030e563301b
    Random 18 bit Crypto Integer: 143815

    Conclusion

    In this Python tutorial, you learned how to generate random data in Python. The Python random module is a straightforward library that provides many methods to generate and play with random data. You can also use the random method to shuffle a sequence of elements, such as shuffling elements from a list, or if we talk about a real application shuffling a deck of cards .

    Apart from the random module we have os and secrets modules in Python which can also be used to generate random data. The os module is generally used to generate Operating System Specific Crypto Bytes code, where we can use the secrets modules to generate secure random data.

    People are also reading:

    Leave a Comment on this Post

    0 Comments