Python: Generate a Dummy List with N Random Elements

Updated: July 4, 2023 By: Khue Post a comment

To generate a dummy list with n random elements in Python, you can use the random module along with list comprehension. Here’s a step-by-step guide:

1. Import the random module:

import random

2. Specify the size of the list, n, and the range of values from which the random elements will be generated.

3. Use a list comprehension to generate the random elements and create the dummy list:

dummy_list = [random.randint(start, end) for _ in range(n)]

In the code snippet above, random.randint(start, end) generates a random integer between start and end (inclusive) for each iteration of the loop, repeated n times. The underscore _ is used as a throwaway variable since its value is not used.

Complete example:

import random

n = 10
start = -10
end = 10

dummy_list = [random.randint(start, end) for _ in range(n)]
print(dummy_list)

My output (yours might be different from mine due to the randomness):

[3, 4, -1, -1, -3, -6, 9, 7, -2, 5]

You can also set a random seed to make the output consistent when re-executing the code:

import random

# set random seed
random.seed(2023)

# other code

That’s it. Happy coding!