At some point in your development journey, you might have to generate random data in Python. In this tutorial, we will see how to do that.

**The Python built-in random module is used to generate random numbers (e.g. integers or floats) within a specific range. It also allows generating strings and lists with random elements. The Numpy library also provides the random module to generate random data structures.**

We will go through multiple ways of applying the Python built-in random module and the Numpy random module.

Let’s start with some examples!

Table of Contents

## How Do you Generate a Random Number Between 0 And 1 in Python?

Python provides a module to generate random numbers: the **random module**.

The most basic method of the random module is the **random method**.

Here is what the random method does, it generates a random float between 0 and 1:

```
>>> import random
>>> random.random()
0.7854170732801697
>>> random.random()
0.7340120513329158
>>> random.random()
0.5851946653258203
```

And what if we want to generate a random float between 0 and 10?

We can use the **random.uniform()** method and pass two arguments that define the beginning and the end of the range.

```
>>> random.uniform(1, 10)
1.6010581832190662
>>> random.uniform(1, 10)
6.788702746057039
>>> random.uniform(1, 10)
8.085425419675126
```

Similarly, to generate a random number between 0 and 100 we use the following command.

```
>>> random.uniform(1, 100)
80.84958257046604
>>> random.uniform(1, 100)
24.326120311951602
>>> random.uniform(1, 100)
41.81256739317393
```

## How to Generate a Random Float Between 0 and 1 using Numpy

The Numpy library also provides a module to generate random numbers.

Here is how you can generate a random number between 0 and 1 using Numpy:

```
>>> import numpy as np
>>> np.random.random()
0.335309649692459
>>> np.random.random()
0.4965360512032966
>>> np.random.random()
0.7790850138688835
```

Numpy also provides the uniform() method that we have seen in the previous section for the Python random built-in module.

Here is how we generate a random float number between 0 and 10 using Numpy:

```
>>> np.random.uniform(0, 10)
6.811695148603444
>>> np.random.uniform(0, 10)
6.888316097297719
>>> np.random.uniform(0, 10)
1.610517388296695
```

Later on, in this tutorial, we will see what else we can do with the Numpy random module.

Now let’s generate random integers…

## Generate a Random Int in Python

The **randint()** method of the Python random built-in module generates a random integer.

Here is what happens when I call the randint method without arguments…

```
>>> random.randint()
Traceback (most recent call last):
File "", line 1, in
random.randint()
TypeError: randint() missing 2 required positional arguments: 'a' and 'b'
```

According to the error, the randint method expects two arguments. We can get more details using the help function.

```
>>> help(random.randint)
Help on method randint in module random:
randint(a, b) method of random.Random instance
Return random integer in range [a, b], including both end points.
```

So, the a and b arguments to be passed to the randint method define the range in which the integer is generated.

With the following command we get back random integers in the range between 1 and 100:

```
>>> random.randint(1, 100)
11
>>> random.randint(1, 100)
32
>>> random.randint(1, 100)
26
```

The built-in random module also provides a method called **randrange**. Let’s find out the difference from the randint method.

This is the help for it:

```
randrange(start, stop=None, step=1, _int=) method of random.Random instance
Choose a random item from range(start, stop[, step]).
```

### Example of numbers generated with randint

```
>>> random.randint(1,3)
1
>>> random.randint(1,3)
3
>>> random.randint(1,3)
3
```

### Example of numbers generated with randrange

```
>>> random.randrange(1,3)
1
>>> random.randrange(1,3)
2
>>> random.randrange(1,3)
2
```

I have used the examples above to show that the **randint **method includes both arguments in the range used to generate the random numbers.

On the other side, the **randrange **method excludes the second argument from the range.

## Generate a List of Random Numbers Using the Random Built-in Module

The following code uses the Python random built-in module and a while loop to generate a list of random integers:

```
>>> random_numbers = []
>>> while len(random_numbers) < 10:
random_numbers.append(random.randint(1, 100))
>>> print(random_numbers)
[49, 2, 37, 9, 43, 26, 89, 71, 60, 41]
```

The code inside the while loop is executed as long as the list has less than 10 numbers.

The next section shows a way to do this with less code…

## Generate a List of Random Numbers Using Numpy

You can also generate a list of random numbers using the Numpy library.

Below you can see some of the methods in the Numpy random module:

```
>>> import numpy as np
>>> np.random.ra
np.random.rand( np.random.randn( np.random.random_integers( np.random.ranf(
np.random.randint( np.random.random( np.random.random_sample( np.random.rayleigh(
```

To generate a list of random integers we can use the randint() method. It has the same name as the method we have seen in the Python built-in random module but it’s more flexible.

```
>>> np.random.randint(1, 10, 10)
array([8, 2, 6, 4, 6, 4, 2, 1, 4, 9])
```

We have passed three arguments to the method. The first two are used to specify the **start (inclusive)** and **end (exclusive)** of the range in which the random integers are generated

The third argument is used to return a Numpy array of 10 elements.

As the third argument, we can also pass a **tuple of integers**. Here is what happens when we do that:

```
>>> np.random.randint(1, 10, (5,5))
array([[4, 1, 9, 3, 4],
[7, 1, 8, 1, 2],
[1, 2, 3, 8, 2],
[9, 1, 3, 6, 8],
[9, 9, 4, 8, 6]])
```

We get back a 5 by 5 multidimensional array (or matrix).

## Get Random Elements From a Python List

With the Python random module, you can also retrieve random elements from a list.

Let’s compare the behavior of the following methods when we pass to them a list of characters:

- random.choice()
- random.choices()
- random.sample()

### Random.choice()

Returns a random element from a sequence.

```
>>> random.choice(['h', 'e', 'l', 'l', 'o'])
'o'
>>> random.choice(['h', 'e', 'l', 'l', 'o'])
'h'
>>> random.choice(['h', 'e', 'l', 'l', 'o'])
'o'
```

## Random.choices()

Returns a list of random elements from a sequence. The default size of the list is 1.

```
>>> random.choices(['h', 'e', 'l', 'l', 'o'])
['l']
>>> random.choices(['h', 'e', 'l', 'l', 'o'])
['o']
>>> random.choices(['h', 'e', 'l', 'l', 'o'])
['o']
```

Here is how we can generate lists with 2 elements. We have to pass a value for the argument k.

```
>>> random.choices(['h', 'e', 'l', 'l', 'o'], k=2)
['o', 'l']
>>> random.choices(['h', 'e', 'l', 'l', 'o'], k=2)
['o', 'h']
>>> random.choices(['h', 'e', 'l', 'l', 'o'], k=2)
['e', 'l']
```

### Random.sample()

It also returns k random elements from a sequence.

When we use the method sample() simply passing the list to it we get back the following error:

```
>>> random.sample(['h', 'e', 'l', 'l', 'o'])
Traceback (most recent call last):
File "", line 1, in
TypeError: sample() missing 1 required positional argument: 'k'
```

That’s because the sample() method requires the k argument to be passed.

```
>>> random.sample(['h', 'e', 'l', 'l', 'o'], k=1)
['l']
>>> random.sample(['h', 'e', 'l', 'l', 'o'], k=2)
['o', 'l']
>>> random.sample(['h', 'e', 'l', 'l', 'o'], k=3)
['h', 'l', 'o']
```

## Generate Random Strings in Python

We can use what we have learned in the previous section to generate a random string of characters.

Let’s start from the following:

`random.choice(['h', 'e', 'l', 'l', 'o'])`

If we apply a list comprehension to the expression above we can create a list of random characters:

```
>>> [random.choice(['h', 'e', 'l', 'l', 'o']) for i in range(5)]
['l', 'o', 'h', 'o', 'l']
```

Now we can apply the string join() method to the list generated before:

```
>>> ''.join([random.choice(['h', 'e', 'l', 'l', 'o']) for i in range(5)])
'holhl'
```

With the sample() method we don’t need a list comprehension considering that sample() already returns a list.

We can generate a random list whose length is 5 characters simply passing k=5.

```
>>> ''.join(random.sample(['h', 'e', 'l', 'l', 'o'], k=5))
'loleh'
```

Before moving to the next section I will show you how to use the string module together with the random module to generate a random numeric string, a random string of letters, and a random alphanumeric string.

### Generate a random numeric string

```
>>> import string
>>> string.digits
'0123456789'
>>> ''.join(random.sample(string.digits, k=5))
'31729'
```

### Generate a random string of letters

```
>>> string.ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> ''.join(random.sample(string.ascii_letters, k=5))
'qOUtD'
```

You can also use **string.ascii_lowercase** or **string.ascii_uppercase** if you don’t want to mix uppercase and lowercase letters.

### Generate a random alphanumeric string

A way to generate an alphanumeric string is by concatenating string.digits and string.ascii_letters.

To concatenate the two strings generated using the string module we will use the + operator.

```
>>> all_characters = string.digits + string.ascii_letters
>>> all_characters
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> ''.join(random.sample(all_characters, k=5))
'R7moj'
```

Makes sense? 🙂

Also, try the same code but this time using **string.printable**. Have a look at what other characters are included in your random string.

## How to Create a Random UUID String in Python

To generate a random UUID in Python you can use the **uuid4 function** of the **uuid module**.

```
>>> import uuid
>>> uuid.uuid4()
UUID('df78ded3-d9f0-419d-a556-78eec59d838b')
>>> type(uuid.uuid4())
<class 'uuid.UUID'>
```

The object we get back is of type uuid.UUID. To convert it into a string we can use the **str() function**.

```
>>> str(uuid.uuid4())
'2bc19645-bb49-45e6-bfc7-f39304e75d27'
```

Below you can see four functions available in the uuid module to generate UUIDs (including uuid4 that we have just used).

## Conclusion

Now you know how to generate random numbers, random strings, and random lists in Python.

Also, just a random question… 😀

What do you need random data for in your application?

Let me know in the comments!

I’m a Tech Lead, Software Engineer and Programming Coach. I want to help you in your journey to become a Super Developer!