Course contentsShow
← Data Science
Lesson 2057 of 2,14547. Reproducible ResearchFree lesson

Setting Seeds in Python and R

Practice setting random seeds using numpy.random.seed(), random.seed(), and set.seed() to control randomness.

Setting Seeds in Python and R

You'll learn how to set random seeds to make your random operations reproducible across Python and R.

Why Set a Seed?

Remember how pseudorandom number generators produce sequences that look random but are actually deterministic? Setting a seed is like choosing the starting point of that sequence. When you set the same seed, you get the same "random" numbers every time. This makes your analysis reproducible—critical when sharing code or debugging models.

Setting Seeds in Python

Python has two main modules for randomness:

For random module:

import random
random.seed(42)
print(random.random())  # Always produces same first value

For numpy (most common in data science):

import numpy as np
np.random.seed(42)
print(np.random.rand())  # Reproducible numpy random values

Note: Modern numpy also supports np.random.default_rng(42) for better practice, but seed-based control remains widely used.

Setting Seeds in R

R uses a single function:

set.seed(42)
runif(1)  # Reproducible uniform random value

Practical Usage Pattern

Set your seed once at the beginning of your script or notebook, before any random operations:

# Python
np.random.seed(123)
# Now all train/test splits, weight initialization, etc. will be reproducible
# R
set.seed(123)
# Now sampling, cross-validation folds, etc. will be reproducible

The actual number (42, 123, etc.) doesn't matter—consistency does.

Key Takeaway: Use np.random.seed(), random.seed(), or set.seed() at the start of your analysis to ensure random operations produce identical results each time, making your work fully reproducible.