1. np.random.rand()

rand() generates random floating-point numbers from: 0.0 ≤ value < 1.0.

import numpy as np

Example 1: Generate one random number

x = np.random.rand() print(x)

Possible output:

0.673421

Every execution can produce a different number.

Example 2: Generate 5 random numbers

x = np.random.rand(5) print(x)

Possible output:

[0.23 0.71 0.45 0.91 0.18]

Shape:

print(x.shape)

Output:

(5,)

So this is a 1-D array containing 5 values.

Example 3: Generate 3 × 3 array

x = np.random.rand(3, 3) print(x)

Possible output:

[[0.21 0.56 0.78] [0.34 0.91 0.12] [0.67 0.43 0.88]]

Shape: 3 rows × 3 columns.

Example 4: Generate 2 × 4 array

x = np.random.rand(2, 4) print(x)

Possible output:

[[0.12 0.45 0.78 0.33] [0.89 0.21 0.67 0.54]]

Example 5: Generate 3-D array

x = np.random.rand(2, 3, 4) print(x)

Shape:

print(x.shape)

Output:

(2, 3, 4)

Think of it as:
2 blocks → 3 rows → 4 columns.


2. Generating random numbers in a specific range

rand() itself only produces values between 0 and 1. But we can use mathematical operations.

Example 6: Random numbers between 0 and 100

x = np.random.rand(5) * 100 print(x)

Possible output:

[23.45 78.21 54.67 91.23 12.89]

Formula:

np.random.rand(5) * 100

Example 7: Random numbers between 10 and 20

Use: low + (high - low) * random

x = 10 + (20 - 10) * np.random.rand(5) print(x)

Possible output:

[12.34 18.76 15.21 19.43 11.87]

Or simply:

x = 10 + 10 * np.random.rand(5)

Example 8: Random numbers between 50 and 100

x = 50 + 50 * np.random.rand(5) print(x)

Possible output:

[72.31 94.21 63.87 81.45 56.92]

Practical Examples

3. Practical Example — Student Marks

Suppose we want random marks between 0 and 100.

marks = np.random.rand(10) * 100 print(marks)

Possible output:

[78.23 45.67 91.22 63.54 82.11 56.78 72.45 88.31 34.67 69.12]

4. Practical Example — Random Percentage

percentage = np.random.rand(5) * 100 print(percentage)

5. Practical Example — Random Temperature

Suppose temperature should be between 20°C and 40°C:

temperature = 20 + 20 * np.random.rand(5) print(temperature)

Possible output:

[27.31 35.82 21.45 38.67 30.12]

6. Practical Example — Random Discount

Generate discounts between 5% and 30%:

discount = 5 + 25 * np.random.rand(5) print(discount)

7. Practical Example — Random Salary

Suppose salary should be between ₹20,000 and ₹50,000:

salary = 20000 + 30000 * np.random.rand(5) print(salary)

Possible output:

[23451.23 41231.67 28765.44 49321.12 35678.91]

8. 2-D Practical Example — Student Marks

Generate marks for 5 students × 3 subjects:

marks = np.random.rand(5, 3) * 100 print(marks)

Possible output:

[[78.2 65.4 91.2] [56.7 72.3 84.5] [91.4 88.2 76.5] [45.6 67.8 71.2] [82.1 93.4 89.7]]

Here: 5 → students, 3 → subjects, 100 → marks scale.


Advanced Usage

9. Convert to Integer

rand() generates floats. If you want integers:

x = (np.random.rand(5) * 100).astype(int) print(x)

Possible output:

[23 78 45 91 12]
But for integer generation, randint() is usually better.

10. Generate Boolean Values

We can use a condition:

x = np.random.rand(10) > 0.5 print(x)

Possible output:

[ True False True True False False True False True True]

This can be useful for generating random yes/no conditions.

11. Generate 0 or 1

x = (np.random.rand(10) > 0.5).astype(int) print(x)

Possible output:

[1 0 1 1 0 0 1 0 1 1]

12. Using seed()

Normally, random values change every time.

print(np.random.rand(5)) print(np.random.rand(5))

The two results will normally be different. If we want repeatable results:

np.random.seed(10) print(np.random.rand(5))

Run the same program again:

np.random.seed(10) print(np.random.rand(5))

You get the same sequence.

Why use seed()? Very useful in:
  • Machine learning
  • Testing
  • Debugging
  • Student demonstrations
  • Reproducible experiments

13. Important Shape Examples

  • np.random.rand() → One value
  • np.random.rand(5) → 1-D array
  • np.random.rand(3, 4) → 2-D array
  • np.random.rand(2, 3, 4) → 3-D array
  • np.random.rand(2, 3, 4, 5) → 4-D array

Complete rand() Cheat Sheet

import numpy as np # One random value np.random.rand() # 5 random values np.random.rand(5) # 3 × 3 np.random.rand(3, 3) # 2 × 4 np.random.rand(2, 4) # 3-D np.random.rand(2, 3, 4) # 0–100 np.random.rand(5) * 100 # 10–20 10 + 10 * np.random.rand(5) # 50–100 50 + 50 * np.random.rand(5) # Boolean np.random.rand(10) > 0.5 # 0/1 (np.random.rand(10) > 0.5).astype(int) # Repeatable random values np.random.seed(10) np.random.rand(5)
One important point
Don't confuse: np.random.rand(3, 4) with np.random.rand((3, 4))

❌ The second form is incorrect for rand().
rand() takes dimensions as separate arguments:
np.random.rand(3, 4)
while random() takes the shape as a tuple:
np.random.random((3, 4))

3. np.random.randn()

randn() generates random numbers according to the standard normal distribution.

The standard normal distribution has:

  • Mean (μ) = 0
  • Standard deviation (σ) = 1
  • Values can be negative, zero, or positive
import numpy as np

Example 1: Generate one random value

x = np.random.randn() print(x)

Possible output:

-0.437

Another execution could give 1.284 or 0.052.
So unlike rand(), the result is not restricted to 0–1.

Example 2: Generate 5 values

x = np.random.randn(5) print(x)

Possible output:

[-0.42 0.83 1.21 -1.34 0.17]

Notice that both positive and negative values are possible.

Example 3: Generate a 3 × 3 matrix

x = np.random.randn(3, 3) print(x)

Possible output:

[[-0.32 0.51 1.24] [ 0.17 -0.83 0.42] [ 1.12 0.06 -1.41]]

Example 4: Generate a 2 × 4 matrix

x = np.random.randn(2, 4) print(x)

Possible output:

[[ 0.34 -1.12 0.75 1.43] [-0.28 0.52 -0.91 0.17]]

Example 5: 3-D Array

x = np.random.randn(2, 3, 4) print(x) print(x.shape)

Output:

(2, 3, 4)

Meaning: 2 blocks → 3 rows → 4 columns.

Example 6: Check Mean

Generate many values:

x = np.random.randn(100000) print(x.mean())

The result will be approximately 0.00. For example: 0.0023.

Why approximately 0? Because randn() follows a distribution whose theoretical mean is 0.

Example 7: Check Standard Deviation

x = np.random.randn(100000) print(x.std())

Output will be approximately 1.0. For example: 1.0021.

This is because the standard deviation of the standard normal distribution is 1.

Example 8: rand() vs randn()

rand()
x = np.random.rand(10) print(x)

Possible: [0.23 0.71 0.45 0.91 0.18 ...]

Values are: 0 ≤ x < 1

randn()
x = np.random.randn(10) print(x)

Possible: [-0.43 1.21 -0.72 0.15 -1.34 ...]

Values can be negative or positive.

Remember:
  • rand() → Uniform distribution between 0 and 1
  • randn() → Standard normal distribution (mean = 0, std = 1)

Generate Data with a Specific Mean

This is an important practical use.

Formula:
value = mean + standard_deviation × random_value

In Python:
mean + std * np.random.randn()

Example 9: Student Marks

Suppose student marks have Mean = 70 and Standard deviation = 10.
We can generate random marks approximately around 70:

marks = 70 + 10 * np.random.randn(10) print(marks)

Possible output:

[64.2 82.4 71.3 58.7 76.1 68.4 91.2 73.5 62.8 79.4]

Example 10: Student Height

Suppose average student height is 165 cm and standard deviation is 8 cm.

height = 165 + 8 * np.random.randn(10) print(height)

This creates values distributed around 165.

Example 11: Temperature

Suppose average temperature is Mean = 30°C and Standard deviation = 3°C.

temperature = 30 + 3 * np.random.randn(10) print(temperature)

Example 12: Salary Simulation

Suppose average salary is ₹50,000 and standard deviation is ₹8,000.

salary = 50000 + 8000 * np.random.randn(10) print(salary)

Example 13: 1000 Student Marks

Suppose we want to simulate marks with Mean = 65 and Standard deviation = 12.

marks = 65 + 12 * np.random.randn(1000) print(marks.mean()) # Approximately: 65 print(marks.std()) # Approximately: 12

This is a good example for explaining normal distribution.


Advanced Examples

Example 14: Using seed()

If you want the same random values every time:

np.random.seed(10) x = np.random.randn(5) print(x)

Run the program again with np.random.seed(10) and you will get the same sequence.

Example 15: Find Positive and Negative Values

x = np.random.randn(20) print(x) print("Positive:") print(x[x > 0]) print("Negative:") print(x[x < 0])

Here we are using Boolean indexing.

Example 16: Count Positive Values

x = np.random.randn(100) positive = np.sum(x > 0) print(positive)

Since the standard normal distribution is centered around zero, approximately half of the values should be positive.

Example 17: Convert to Integer

x = np.random.randn(10) x = x.astype(int) print(x)

Possible output: [ 0 -1 0 1 0 -2 1 0 0 -1]

⚠️ This truncates the decimal portion. It doesn't round normally.

Example 18: Generate a Random Error

This is a nice real-world example. Suppose predicted values have random measurement errors:

error = np.random.randn(10) print(error)

You can add this error to some actual values:

actual = np.array([100, 120, 150, 130, 180]) error = np.random.randn(5) predicted = actual + error print(predicted)

This is conceptually useful in statistics and machine learning.


Most Important Pattern

If you remember only one thing about randn(), remember:

np.random.randn()

means: Generate random values from a standard normal distribution.


And:

mean + std * np.random.randn(n)

means: Generate n random values approximately centered around the specified mean with the specified standard deviation.

For example:

data = 100 + 15 * np.random.randn(1000)

means: Mean ≈ 100, Standard deviation ≈ 15, Number of values = 1000

rand() vs randn() — Final Comparison

Feature rand() randn()
Distribution Uniform Normal
Typical range 0 to 1 No fixed range
Negative values ❌ ✅
Mean 0.5 0
Standard deviation ≈ 0.289 1
Example rand(5) randn(5)

4. np.random.randint()

randint() is used to generate random integer values.

import numpy as np

Syntax

np.random.randint(low, high=None, size=None, dtype=int)
The most important rule
low is included, high is excluded.

So: np.random.randint(1, 10) can generate: 1, 2, 3, 4, 5, 6, 7, 8, 9 but never 10.

Example 1 — One random integer

x = np.random.randint(10) print(x)

Possible output: 7

Here np.random.randint(10) means: 0 ≤ x < 10. So possible values are 0 to 9.

Example 2 — Between 1 and 10

x = np.random.randint(1, 10) print(x)

Possible output: 6 (Possible values: 1 to 9)

Example 3 — Between 1 and 100

x = np.random.randint(1, 100) print(x)

Possible output: 73 (Possible values: 1 to 99)

Example 4 — Generate 5 random integers

x = np.random.randint(1, 100, 5) print(x)

Possible output: [23 87 45 12 76]

Here:
1 → minimum
100 → maximum exclusive
5 → number of values

Example 5 — Generate 10 random integers

x = np.random.randint(1, 101, 10) print(x)

Possible output: [78 23 91 45 67 12 88 34 56 72]

Why 101? Because the upper limit is excluded. randint(1, 101) gives 1 to 100.

Example 6 — size as a tuple

You can generate a 2-D array.

x = np.random.randint(1, 101, size=(3, 4)) print(x)

Possible output:

[[23 78 45 91] [34 67 12 88] [56 72 39 64]]

Shape: 3 rows × 4 columns.

Example 7 — 3 × 3 Matrix

x = np.random.randint(1, 10, size=(3, 3)) print(x)

Possible output:

[[3 8 2] [7 1 5] [4 9 6]]

Example 8 — 3-D Array

x = np.random.randint(1, 10, size=(2, 3, 4)) print(x) print(x.shape)

Output: (2, 3, 4) (Meaning: 2 blocks, 3 rows, 4 columns).


Practical Examples

Example 9 — Student Marks

Generate marks for 10 students:

marks = np.random.randint(0, 101, 10) print(marks)

Possible output: [78 91 56 83 42 67 88 34 72 95]

Because: 0 ≤ marks ≤ 100. We use 101 because 101 is excluded.

Example 10 — Dice

A dice has values: 1 2 3 4 5 6. Generate one dice roll:

dice = np.random.randint(1, 7) print(dice)

Generate 10 dice rolls:

dice = np.random.randint(1, 7, 10) print(dice)

Possible output: [3 6 2 1 4 5 3 6 2 4]

This is a very good practical example for students.

Example 11 — Coin Toss

We can represent: 0 → Tail, 1 → Head

coin = np.random.randint(0, 2) print(coin)

Generate 10 tosses:

coin = np.random.randint(0, 2, 10) print(coin)

Possible output: [1 0 1 1 0 0 1 0 1 1]

Example 12 — Random Age

Generate random ages between 18 and 60:

age = np.random.randint(18, 61, 10) print(age)

Notice 61 is used to include 60.

Example 13 — Random Year

Generate years between 2000 and 2026:

year = np.random.randint(2000, 2027, 10) print(year)

Example 14 — Random Roll Numbers

Suppose roll numbers are between 1 and 50:

roll = np.random.randint(1, 51, 10) print(roll)
⚠️ Duplicates are possible. For example: [12 45 12 27 18] is perfectly possible.

Example 15 — Random Product Quantity

Suppose an order can contain 1–20 items:

quantity = np.random.randint(1, 21, 10) print(quantity)

Example 16 — Random Price

Generate integer prices between ₹100 and ₹1000:

price = np.random.randint(100, 1001, 10) print(price)

Example 17 — Random Password Digits

Generate a 6-digit numeric code:

otp = np.random.randint(0, 10, 6) print(otp)

To display as one number/string:

otp = np.random.randint(0, 10, 6) otp = ''.join(map(str, otp)) print(otp)

Possible output: 729148

For real authentication/security purposes, however, use a cryptographically secure random generator rather than NumPy's PRNG.

Example 18 — Random Binary Values

Generate only 0 and 1:

x = np.random.randint(0, 2, 10) print(x)

Useful for: Binary classification examples, Boolean-like data, Machine-learning demonstrations.


Advanced Examples & Statistics

Example 19 — dtype

You can specify the integer type:

x = np.random.randint(1, 100, 5, dtype=np.int32) print(x) print(x.dtype)

Output: int32

Example 20 — Using seed()

np.random.seed(10) print(np.random.randint(1, 100, 5))

Running the same code again with the same seed gives the same sequence. Useful for Testing, Debugging, Machine learning, Classroom demonstrations.

Example 21 — Find Maximum and Minimum

marks = np.random.randint(0, 101, 20) print(marks) print("Maximum:", marks.max()) print("Minimum:", marks.min())

Example 22 — Random Matrix and Statistics

marks = np.random.randint(0, 101, 20) print("Marks:", marks) print("Mean:", marks.mean()) print("Maximum:", marks.max()) print("Minimum:", marks.min())

This is a nice combination of random generation + NumPy array operations.

Example 23 — Generate a 5 × 5 Matrix

matrix = np.random.randint(1, 10, size=(5, 5)) print(matrix)

Possible output:

[[4 8 2 7 3] [1 5 9 2 6] [7 3 4 8 1] [9 6 2 5 7] [3 1 8 4 9]]

Example 24 — Random Numbers with low Only

np.random.randint(5, size=10)

means: 0 ≤ value < 5. So np.random.randint(5) and np.random.randint(0, 5) are equivalent in this basic case.


Most Important Syntax

  • One value:
    np.random.randint(10) → 0–9
  • Range:
    np.random.randint(10, 20) → 10–19
  • Multiple values:
    np.random.randint(10, 20, 5) → 5 random integers
  • 2-D array:
    np.random.randint(10, 20, size=(3, 4)) → 3 × 4 random integer matrix
  • 3-D array:
    np.random.randint(10, 20, size=(2, 3, 4)) → 2 × 3 × 4 array

rand() vs randn() vs randint()

Function Data Example
rand() Float 0–1 np.random.rand(5)
randn() Normal distribution np.random.randn(5)
randint() Integer range np.random.randint(1, 100, 5)
One rule students must remember
np.random.randint(1, 10) means 1 ≤ value < 10.

10 is NOT included.
So if you want 1 to 10, write: np.random.randint(1, 11)

5. np.random.random()

np.random.random() generates random floating-point numbers between 0 and 1.

import numpy as np
Basic rule
0.0 ≤ value < 1.0
So 1.0 is never included.

Example 1 — One random number

x = np.random.random() print(x)

Possible output: 0.673421

Example 2 — Generate 5 random numbers

x = np.random.random(5) print(x) print(x.shape)

Possible output: [0.23 0.71 0.45 0.91 0.18]
Shape: (5,)

Example 3 — 3 × 3 array

x = np.random.random((3, 3)) print(x)

Possible output:

[[0.21 0.56 0.78] [0.34 0.91 0.12] [0.67 0.43 0.88]]
⚠️ Notice the tuple: np.random.random((3, 3))

Example 4 — 2 × 4 array

x = np.random.random((2, 4)) print(x)

Example 5 — 3-D Array

x = np.random.random((2, 3, 4)) print(x) print(x.shape)

Output: (2, 3, 4)


Generating values in a specific range

Example 6 — Random values between 0 and 100

random() itself produces 0–1. Multiply by 100:

x = np.random.random(5) * 100 print(x)

Possible output: [23.45 78.21 54.67 91.23 12.89]

Example 7 — Random values between 10 and 20

Use the formula: low + (high - low) × random

x = 10 + (20 - 10) * np.random.random(5) print(x)

Simplified:

x = 10 + 10 * np.random.random(5)

Example 8 — Random values between 50 and 100

x = 50 + 50 * np.random.random(5) print(x)

Practical Examples

Example 9 — Student Percentage

Generate random percentages for 10 students:

percentage = np.random.random(10) * 100 print(percentage)

Example 10 — Student Marks

Generate marks between 0 and 100:

marks = np.random.random(5) * 100 print(marks)

If you need integer marks, use:

marks = (np.random.random(5) * 101).astype(int) print(marks)

But for integer marks, randint() is cleaner: marks = np.random.randint(0, 101, 5)

Example 11 — Temperature

Generate temperatures between 20°C and 40°C:

temperature = 20 + 20 * np.random.random(10) print(temperature)

Example 12 — Discount

Generate discounts between 5% and 30%:

discount = 5 + 25 * np.random.random(5) print(discount)

Example 13 — Salary

Generate random salary values between ₹20,000 and ₹50,000:

salary = 20000 + 30000 * np.random.random(5) print(salary)

Example 14 — 2-D Student Marks

Suppose: 5 students, 3 subjects, marks from 0–100:

marks = np.random.random((5, 3)) * 100 print(marks)

Example 15 — Boolean Values

We can use a condition:

x = np.random.random(10) > 0.5 print(x)

This gives approximately a 50/50 split.

Example 16 — Generate 0 and 1

Convert the Boolean values to integers:

x = (np.random.random(10) > 0.5).astype(int) print(x)

Possible output: [1 0 1 1 0 0 1 0 1 1]

Example 17 — seed()

To reproduce the same random values:

np.random.seed(10) x = np.random.random(5) print(x)

Example 18 — Find Maximum and Minimum

x = np.random.random(10) print(x) print("Maximum:", x.max()) print("Minimum:", x.min())

Example 19 — Mean

x = np.random.random(10000) print(x.mean())

The result should be approximately 0.5. Because values are uniformly distributed between 0 and 1.

Example 20 — Generate Random Matrix

matrix = np.random.random((4, 4)) print(matrix)

Comparisons

random() vs rand()

These two are very similar. Both produce random floats between 0 and 1. The main difference is syntax.

rand() - separate arguments:

np.random.rand(3, 4)

random() - tuple argument:

np.random.random((3, 4))
random() vs randint()

random() → Floating-point values

np.random.random(5)

randint() → Integer values

np.random.randint(1, 10, 5)

Quick Cheat Sheet

# One value np.random.random() # 5 values np.random.random(5) # 3 × 3 np.random.random((3, 3)) # 2 × 4 np.random.random((2, 4)) # 0–100 np.random.random(5) * 100 # 10–20 10 + 10 * np.random.random(5) # 50–100 50 + 50 * np.random.random(5) # Boolean np.random.random(10) > 0.5 # 0/1 (np.random.random(10) > 0.5).astype(int) # Repeatable np.random.seed(10) np.random.random(5)
Important distinction
  • rand() → random floats, shape as separate arguments
  • randn() → normal-distribution values
  • randint() → random integers
  • random() → random floats, shape usually as tuple

6. np.random.choice()

np.random.choice() is used to randomly select values from an array or sequence.

import numpy as np

Syntax

np.random.choice(a, size=None, replace=True, p=None)
Parameter Meaning
a Values or integer range to choose from
size Number/shape of values to select
replace Whether the same value can be selected again
p Probability of selecting each value

Example 1 — Select one value

a = np.array([10, 20, 30, 40, 50]) x = np.random.choice(a) print(x)

Possible output: 30

Example 2 — Select one value from a list

You don't have to create a NumPy array first.

x = np.random.choice([10, 20, 30, 40, 50]) print(x)

Example 3 — Select multiple values

a = np.array([10, 20, 30, 40, 50]) x = np.random.choice(a, 3) print(x)

Possible output: [40 10 30]. Here, 3 means select 3 values.

Example 4 — Duplicate values are possible

By default: replace=True

a = np.array([10, 20, 30]) x = np.random.choice(a, 10) print(x)

Possible output: [20 10 20 30 10 10 30 20 30 10]. Notice 10, 20, and 30 are repeated.

Example 5 — replace=False

If you don't want duplicates:

a = np.array([10, 20, 30, 40, 50]) x = np.random.choice(a, 3, replace=False) print(x)

Possible output: [40 10 30]. Every selected value is unique.

Important: replace=False means once a value is selected, it cannot be selected again.

Example 6 — Select all values randomly

a = np.array([10, 20, 30, 40, 50]) x = np.random.choice(a, 5, replace=False) print(x)

This is basically a random shuffle of the elements.


Practical Examples

Example 7 — Random Student

students = ["Rahul", "Amit", "Neha", "Priya", "Ravi"] student = np.random.choice(students) print(student)

Possible output: Priya. Very useful classroom example: Randomly select one student for an activity.

Example 8 — Random Student Group

students = ["Rahul", "Amit", "Neha", "Priya", "Ravi"] group = np.random.choice(students, 3, replace=False) print(group)

Example 9 — Coin Toss

result = np.random.choice(["Heads", "Tails"]) print(result)

Example 10 — Multiple Coin Tosses

result = np.random.choice(["Heads", "Tails"], 10) print(result)

Example 11 — Dice

dice = np.random.choice([1, 2, 3, 4, 5, 6]) print(dice)

Multiple rolls:

dice = np.random.choice([1, 2, 3, 4, 5, 6], 10) print(dice)

Using Probabilities (p Parameter)

Example 12 — p Parameter

p allows us to specify the probability of each value.

Suppose: A → 70%, B → 20%, C → 10%

x = np.random.choice(["A", "B", "C"], p=[0.7, 0.2, 0.1]) print(x)

The probabilities must add up to 1: 0.7 + 0.2 + 0.1 = 1

Example 13 — Multiple selections with probability

x = np.random.choice(["A", "B", "C"], 10, p=[0.7, 0.2, 0.1]) print(x)

Because A has the highest probability, it will tend to occur more often.

Example 14 — Weighted Student Selection

Suppose we want to select students with different probabilities:

students = ["Rahul", "Amit", "Neha"] selected = np.random.choice(students, 1, p=[0.6, 0.3, 0.1]) print(selected)

More Practical Scenarios

Example 15 — Random Color

colors = ["Red", "Green", "Blue", "Yellow"] color = np.random.choice(colors) print(color)

Example 16 — Random Day

days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] day = np.random.choice(days) print(day)

Example 17 — Random Product

products = ["Laptop", "Mobile", "Tablet", "Headphone"] product = np.random.choice(products) print(product)

Example 18 — 2-D Output

size can be a tuple.

a = np.array([10, 20, 30, 40, 50]) x = np.random.choice(a, size=(2, 3)) print(x)

Duplicates are possible because default is replace=True.

Example 19 — 3-D Output

a = np.array([1, 2, 3, 4, 5]) x = np.random.choice(a, size=(2, 3, 4)) print(x.shape) # (2, 3, 4)

Example 20 — Random Lottery Numbers

Suppose lottery numbers are from 1–50 and we want 6 unique numbers:

numbers = np.arange(1, 51) lottery = np.random.choice(numbers, 6, replace=False) print(lottery)

Example 21 — Random Exam Question

questions = np.arange(1, 11) selected = np.random.choice(questions, 3, replace=False) print(selected)

Example 22 — Random Team Selection

students = ["A", "B", "C", "D", "E", "F"] team1 = np.random.choice(students, 3, replace=False) print("Team 1:", team1)

Example 23 — a as an Integer

An interesting shortcut:

x = np.random.choice(5) print(x)

This chooses from 0, 1, 2, 3, 4. It is equivalent to choosing from np.arange(5).

Example 24 — choice() with replace=False Error

a = [10, 20, 30] np.random.choice(a, 5, replace=False)
⚠️ This will produce an error because you cannot select 5 unique values from only 3 values.

Example 25 — Seed

np.random.seed(10) x = np.random.choice([10, 20, 30, 40, 50], 3) print(x)

Most Important Examples

# Select one np.random.choice([10, 20, 30]) # Select 3 np.random.choice([10, 20, 30, 40, 50], 3) # Select 3 without repetition np.random.choice([10, 20, 30, 40, 50], 3, replace=False) # Select with probability np.random.choice(["A", "B", "C"], p=[0.5, 0.3, 0.2]) # Select 2 × 3 array np.random.choice([10, 20, 30, 40, 50], size=(2, 3))

Final Comparison of All 5

Function Main purpose Example
rand() Random float 0–1 np.random.rand(3,3)
randn() Normal distribution np.random.randn(3,3)
randint() Random integers np.random.randint(1,100,5)
random() Random float 0–1 np.random.random((3,3))
choice() Select from given values np.random.choice([10,20,30])
Important Modern NumPy Note

For new code, NumPy recommends the newer np.random.default_rng() API rather than relying on the older global np.random.* functions. However, understanding the global functions remains essential for reading and maintaining existing codebases.