Python random

generate random float between 0 and 1 - random()

import random

print(random.random())
# output: 0.607414853052997

generate random integer beween two numbers - randint(a, b)

import random

print(random.randint(1, 10))
# output: 8
print(random.randint(1, 10))
# output: 5

select a random element from a sample - choice([i1, i2, ...])

  • lets take sample of fruites ["apple", "banana", "orange", "grapes"] and select a fruit randomly
import random

print(random.choice(["apple", "banana", "orange", "grapes"]))
# output: orange

select k number of random elements from a sample - sample([i1, i2 ,...], k=n)

  • data sample ["apple", "banana", "orange", "grapes"]
  • select 3 random elements from above data sample
import random

print(random.sample(["apple", "banana", "orange", "grapes"], k=3))
# output: ['grapes', 'banana', 'orange']

shuffle the given data sample - shuffle(data)

  • data sample [1,2,3,4,5]
import random

numbers = [1,2,3,4,5]
random.shuffle(numbers)
print(numbers)
# output: [5, 1, 4, 2, 3]
  • If we look at the output we can see that the sample numbers has been shuffled.

generate random number between two numbers - uniform(n1, n2)

  • let's write a simple code to generate random number between two given number inclusive.
import random

n1 = 10
n2 = 20
print(random.uniform(n1, n2))
# output: 19.69388160404919
print(random.uniform(n1, n2))
# output: 16.13326820546709

References: