Python: Generate an Array of Random Numbers
In this article
You can generate an array of random numbers in Python in one line with the standard library: import random, then random.choices(range(1, 101), k=10) gives a list of 10 random integers between 1 and 100. If you need NumPy-style arrays, use numpy.random.default_rng().integers(1, 101, size=10). Neither needs an install for the standard library, and both produce a plain Python list or NumPy array you can loop over, slice or feed into other code.
What You'll Need
- Python 3 installed (any recent 3.x version works; the
randommodule is part of the standard library). - A way to run Python: IDLE, a terminal, VS Code, or a Jupyter notebook.
- Optional: NumPy installed (
pip install numpy) if you want true array objects with vectorised operations.
Step-by-Step
- Import the random module. At the top of your script, add
import random. This is built into Python, so there is nothing to install. If you plan to use NumPy, also addimport numpy as np. - Decide on the range and count. Write down the smallest and largest values you want and how many numbers you need. For example, 10 integers between 1 and 100 inclusive. Knowing this first avoids off-by-one mistakes later.
- Generate integers with
random.randintin a loop. The clearest method for a fixed count is a list comprehension:nums = [random.randint(1, 100) for _ in range(10)].randintincludes both endpoints, so 1 and 100 can appear. - Or use
random.choicesfor a one-liner.nums = random.choices(range(1, 101), k=10)returns 10 integers. Note thatrange(1, 101)stops at 100 becauserangeexcludes its upper bound.choicessamples with replacement, so duplicates are allowed. - Generate floats if you need decimals. Use
random.uniform(0, 1)inside a comprehension:nums = [random.uniform(0, 1) for _ in range(10)].uniformreturns a float between the two bounds. - Pick unique numbers when duplicates are a problem. Use
random.sample(range(1, 101), k=10).sampledraws without replacement, so every value is different. It raises an error ifkis larger than the population. - Use NumPy for a real array. Create a generator with
rng = np.random.default_rng(), thenarr = rng.integers(1, 101, size=10)for integers orrng.random(10)for floats between 0 and 1. NumPy's upper bound is exclusive, so 101 is not included. - Print or store the result. Run
print(nums)to check the output, or save it withwith open('nums.txt', 'w') as f: f.write(str(nums)). For NumPy,np.savetxt('nums.txt', arr)writes one value per line. - Make results repeatable with a seed. Call
random.seed(42)before generating, ornp.random.default_rng(42)for NumPy. The same seed produces the same sequence every run, which is useful for tests and tutorials. - Run the script and verify. Execute it from the terminal with
python yourfile.py. Check that the count matches, the values fall inside your range, and the type is what you expected (list vs. NumPy array).
Common Mistakes
- Off-by-one with
range.range(1, 100)stops at 99. Userange(1, 101)if you want 100 included. - Confusing
randintandrandrange.randint(a, b)includes both ends;randrange(a, b)excludesb. - Using
random.samplewhen duplicates are fine. It will error if you ask for more unique values than the range contains. - Expecting
numpy.random.randintto include the upper bound. NumPy'sintegersandrandintexclude the high value, unlike Python'srandom.randint. - Forgetting to seed when comparing runs. Without a seed, every run differs, which can look like a bug in tests.
- Assuming
randomis cryptographically secure. For passwords or tokens, use thesecretsmodule instead.
Tips
- Prefer
random.choicesor a list comprehension overforloops withappend; they are shorter and faster to read. - Use
random.shuffleif you already have a list and just want the order randomised. - For weighted picks, pass a
weightslist torandom.choices. - NumPy arrays are faster for large counts and support vectorised maths, but a plain list is fine for small scripts.
- Store the seed in a variable so you can change it in one place when testing.
- If you need a fixed shape for machine learning, NumPy's
size=(rows, cols)argument builds a 2D array in one call.
Troubleshooting
ModuleNotFoundError: No module named 'numpy'— NumPy is not installed. Runpip install numpyin the same environment you are running the script from. If you use a virtual environment, activate it first.- Values outside your expected range — check whether you used
randint(inclusive) orrandrange/NumPy (exclusive). Adjust the upper bound by one. ValueError: Sample larger than population—random.sampleasked for more unique values than the range holds. Widen the range or switch tochoices.- Same numbers every run — a seed is set somewhere in your code or environment. Remove or change
random.seed(...). - Different numbers every run when you wanted the same — add a seed at the start of the script, before any random call.
- Output is a NumPy array but you expected a list — wrap it with
.tolist()or use the standardrandommodule instead.
Frequently Asked Questions
How do I generate 10 random numbers between 1 and 100 in Python?
Use [random.randint(1, 100) for _ in range(10)]. Both endpoints are included, so 1 and 100 can appear.
What is the difference between random.randint and random.randrange?
randint(a, b) includes b. randrange(a, b) stops before b, the same way range does.
How do I get unique random numbers?
Use random.sample(range(1, 101), k=10). It draws without replacement, so no value repeats.
Can I generate random floats instead of integers?
Yes. Use random.uniform(a, b) for a float between two bounds, or random.random() for a float between 0 and 1.
How do I make the output reproducible?
Call random.seed(42) before generating, or pass a seed to np.random.default_rng(42). The same seed gives the same sequence.
Is the random module safe for passwords?
No. It is not cryptographically secure. Use the secrets module for tokens, passwords and anything security-related.