random

What it is good for?

Generate random numbers.

random contains generators for the most common distributions.

Installed with Python by default

yes

Example

Creating random integers

One most wanted function is to create random integers in a given range:

  1. dice = random.randint(1,6)

Creating random floats

The random() functin generates float numbers between 0 and 1:

  1. import random
  2. print random.random()

Generate random numbers from a few distributions.

  1. import random
  2. random.randint(1,6)
  3. random.random()
  4. random.gauss(0.0, 1.0)

Shuffle a list

  1. data = [1, 2, 3, 4]
  2. random.shuffle(data)

Creating random lists

Random combinations of elements with repetition:

  1. from random import choice
  2. bases = ['A','C','G','T']
  3. dna = [choice(bases) for i in range(20)]
  4. print ''.join(dna)

When elements are to be picked without repetition, you would use, the sample function:

  1. from random import sample
  2. flavors = ['vanilla','banana','mint']
  3. icecream = sample(flavors, 2)

Where to learn more?

https://docs.python.org/3/library/random.html