Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Python: Generate an Array of Random Numbers

· 5 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

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 random module 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

  1. 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 add import numpy as np.
  2. 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.
  3. Generate integers with random.randint in a loop. The clearest method for a fixed count is a list comprehension: nums = [random.randint(1, 100) for _ in range(10)]. randint includes both endpoints, so 1 and 100 can appear.
  4. Or use random.choices for a one-liner. nums = random.choices(range(1, 101), k=10) returns 10 integers. Note that range(1, 101) stops at 100 because range excludes its upper bound. choices samples with replacement, so duplicates are allowed.
  5. Generate floats if you need decimals. Use random.uniform(0, 1) inside a comprehension: nums = [random.uniform(0, 1) for _ in range(10)]. uniform returns a float between the two bounds.
  6. Pick unique numbers when duplicates are a problem. Use random.sample(range(1, 101), k=10). sample draws without replacement, so every value is different. It raises an error if k is larger than the population.
  7. Use NumPy for a real array. Create a generator with rng = np.random.default_rng(), then arr = rng.integers(1, 101, size=10) for integers or rng.random(10) for floats between 0 and 1. NumPy's upper bound is exclusive, so 101 is not included.
  8. Print or store the result. Run print(nums) to check the output, or save it with with open('nums.txt', 'w') as f: f.write(str(nums)). For NumPy, np.savetxt('nums.txt', arr) writes one value per line.
  9. Make results repeatable with a seed. Call random.seed(42) before generating, or np.random.default_rng(42) for NumPy. The same seed produces the same sequence every run, which is useful for tests and tutorials.
  10. 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. Use range(1, 101) if you want 100 included.
  • Confusing randint and randrange. randint(a, b) includes both ends; randrange(a, b) excludes b.
  • Using random.sample when duplicates are fine. It will error if you ask for more unique values than the range contains.
  • Expecting numpy.random.randint to include the upper bound. NumPy's integers and randint exclude the high value, unlike Python's random.randint.
  • Forgetting to seed when comparing runs. Without a seed, every run differs, which can look like a bug in tests.
  • Assuming random is cryptographically secure. For passwords or tokens, use the secrets module instead.

Tips

  • Prefer random.choices or a list comprehension over for loops with append; they are shorter and faster to read.
  • Use random.shuffle if you already have a list and just want the order randomised.
  • For weighted picks, pass a weights list to random.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. Run pip install numpy in 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) or randrange/NumPy (exclusive). Adjust the upper bound by one.
  • ValueError: Sample larger than population — random.sample asked for more unique values than the range holds. Widen the range or switch to choices.
  • 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 standard random module 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.