How To Use Random In Python

In this tutorial, you will learn how to use the random module in Python to generate random numbers, shuffle lists, and obtain random elements from a given sequence. This can be useful in various applications such as games, simulations, and random decision-making.

Step 1: Import the random module

To start using the random module in your code, you need to first import it. Simply add the following line at the beginning of your code:

Step 2: Generate random numbers

After importing the module, you can use the various functions available in the random module to generate random numbers. Some of the most commonly used functions are:

  1. random.random(): This function returns a random float number in the range [0.0, 1.0).
  1. random.uniform(a, b): This function returns a random float number in the range [a, b].
  1. random.randint(a, b): This function returns a random integer in the range [a, b], including both ends.

Step 3: Select random elements from a sequence

To select random elements from a given sequence like a list, you can use the below functions in the random module:

  1. random.choice(sequence): This function returns a randomly selected element from the given sequence.
  1. random.choices(sequence, weights=None, k=1): This function returns a list of k elements randomly selected from the sequence. You can optionally provide weights for the elements to influence their probability of being selected.
  1. random.sample(sequence, k): This function returns a list of unique elements randomly selected from the sequence.

Step 4: Shuffle a sequence

To shuffle elements in a list, you can use the random.shuffle() function. Keep in mind that this function shuffles the list in place, meaning it does not create a new list, but rather rearranges the elements in the original list.

Example Code

Here is the complete code combining the steps and the examples above:

Example Output

Random number between 0 and 1: 0.582181286279
Random number between 1 and 10: 4.20274682812
Random integer between 1 and 10: 6
Random name: Alice
Random names: ['Charlie', 'Bob']
Random unique names: ['David', 'Bob']
Shuffled numbers: [7, 3, 8, 9, 5, 2, 6, 1, 4]

Conclusion

Now you know how to use the random module in Python to generate random numbers, select random elements from a sequence, and shuffle lists. This module is very useful in various applications where randomness is required.

Remember that the numbers generated by the random module are pseudorandom, meaning they are generated with a deterministic algorithm and are not suitable for cryptographic purposes.

If you need cryptographically secure random numbers, you should use the secrets module instead.