Site Tools


import-random

Table of Contents

import random

import random is a Python import that generates pseudo-random numbers. Use it for shuffling, sampling, and generating random values for simulations and games.

Example

# Python
# description: random numbers, shuffling, sampling

import random

# Random float between 0 and 1
x = random.random()
print(x)  # 0.37...

# Random integer in range
die_roll = random.randint(1, 6)
print(die_roll)

# Random choice from list
choice = random.choice(["apple", "banana", "cherry"])
print(choice)

# Shuffle list in-place
numbers = [1, 2, 3, 4, 5]
random.shuffle(numbers)
print(numbers)

# Sample without replacement
sample = random.sample(range(100), 5)
print(sample)

# Random float in range
x = random.uniform(0, 10)
print(x)

Common functions

  • random.random(): random float [0.0, 1.0)
  • random.randint(a, b): random integer in range [a, b]
  • random.uniform(a, b): random float in range [a, b]
  • random.choice(seq): random element from sequence
  • random.choices(seq, k=n): n random elements with replacement
  • random.sample(seq, k=n): n random elements without replacement
  • random.shuffle(list): shuffle list in-place
  • random.seed(n): set seed for reproducible results
import-random.md ยท Last modified: