Unlocking the Mysteries of Python's 'random' Library


Welcome data science enthusiasts! We are about to embark on an exciting journey through the fantastic world of the random library in Python. Get ready to infuse your code with a touch of randomness and unpredictability. Through vivid code examples and engaging narratives, we will explore the features and capabilities of the random library in Python.

Unlocking the Power of random

In Python, the random library is a tool that introduces randomness, which allows us to generate random numbers and manipulate collections. Let's kick things off by importing the random library!

import random

Now that we've got the random library at our disposal, let's explore its functions and integrate this extraordinary library into your coding projects!

Diving into Random Numbers

The Data Science Duo's Monopoly Night

The Data Science Duo gathered around their old, worn Monopoly board for what was anticipated to be a traditional game night. However, excitement quickly turned to confusion when Professor Karle reached into the Monopoly box and discovered that the dice were missing. "How could this be?" she exclaimed.

Discovering Random Floats

Would the Data Science Duo still be able to enjoy their game night? Of course! Professor Wade introduced the random() function to Professor Karle. It is a uniform distribution, which means every number within the specified range has an equal chance of being generated.

# This function generates random floats between 0.0 (inclusive) and 1.0 (exclusive)
random_float = random.random()
random_float
0.7928345613872408

Unleashing Random Integers

"But that's not a real die. You would never see a die that has a 0.7928345613872408 on one of its sides!" exclaimed Professor Karle. "I want a real die!"

How could the Data Science Duo construct a real die?

They could generate random integers within a specified range using the randint function.

# This function gives you a random integer between 1 and 6
ProfWade_die = random.randint(1, 6) 
ProfWade_die
5
# This function  gives you a random integer between 1 and 6
ProfKarle_die = random.randint(1, 6) 
ProfKarle_die
2

It seems like Professor Wade has a lead!

The Magic of Random Choices

The Data Science Duo decided to grab some fruits from the fruit bowl on the table as their snacks. But they had no idea what to choose as if every thought had suddenly evaporated into thin air after the long, exciting Monopoly game. "Why don't we use the random library to help us decide?" Professor Wade suggested.

The random library supports more than just generating random integers, which means that the Data Science Duo can also use it for lists, strings, or booleans. For instance, the following function helps the Data Science Duo choose a random fruit from the fruit bowl.

# All the fruits in the fruit bowl are collected as a list 
# and stored in the variable "fruits"
fruits = ['apple', 'banana', 'cherry', 'peach', 'strawberry']
# This function selects a random fruit from the "fruits" list for Karle
random_fruit_Karle = random.choice(fruits)  
# This function selects a random fruit from the "fruits" list for Wade
random_fruit_Wade = random.choice(fruits)  
print(f"Randomly Chosen Fruit For Karle: {random_fruit_Karle}")
print(f"Randomly Chosen Fruit For Wade: {random_fruit_Wade}")
Randomly Chosen Fruit For Karle: cherryRandomly Chosen Fruit For Wade: apple

Shuffling A Deck of Cards

After the Data Science Duo had a few snacks, they decided to play a card game called 107, invented by Professor Karle. The objective of the game is to accumulate a hand with points as close to 7 as possible to win. Despite their unfamiliarity with manually shuffling a deck of cards, they used the shuffle function from the random library to shuffle the cards. After a quick discussion, Professor Wade decided to take the odd-numbered cards, while Professor Karle chose the even-numbered cards.

Python's random library provides the shuffle function, which rearranges the elements in a list in a random order. Shuffling is a process used to randomize the order of elements in a collection which ensures that data does not carry any unintentional bias due to its original ordering.

# "my_list" contains the next four cards from the deck
my_list = [6, 3, 1, 2]
# This function randomly reorders the elements of a list
random.shuffle(my_list) 
print("Shuffled List:", my_list)
Shuffled List : [2, 3, 6, 1]

It seemed like Professor Wade was winning again since he got 6 and 1 which is exactly 7 points. Meanwhile, Professor Karle only got 3 and 2, which is two points away from winning.

The Secret of the Randomness

Wait?! How could Professor Wade be this lucky again?!?! How is this possible???

# This function initializes the random number generator to a known state
random.seed(42)  

random.seed makes random.randint no longer random, which means Professor Wade has a higher chance of winning the game if he uses certain seed. For instance, setting a seed value such as random.seed(42) ensures your random outcomes are repeatable. While it doesn't change anything immediately, it guarantees that functions like random.random() or random.randint(...) produce the same results every time you run your program, making your random processes predictable and consistent.

Energetic Examples

Example 1: Generating Random Numbers

Here, we will generate a random number between 7 and 1000 and store it in random_integer. Let's try it out!

import random
# Generate a random integer between 7 and 1000
random_integer = random.randint(7, 1000)
random_integer
107

Example 2: Randomly Shuffling a Playlist

Here, we will shuffle the songs in the taylor_swift_songs list and print the shuffled list.
Let's try it out!

import random

# This function stores all the songs into the list "taylor_swift_songs"
taylor_swift_songs = ["Blank Space","Love Story","Shake It Off","Cardigan","Lover","Bad Blood","All Too Well","Delicate"]
# This function reorders the songs in that list randomly
random.shuffle(taylor_swift_songs)
taylor_swift_songs
['Bad Blood', 'Blank Space', 'Love Story', 'All Too Well', 'Cardigan', 'Delicate', 'Shake It Off', 'Lover']

Example 3: Random Choice to Help Decide Which Movie to Watch

Here, we will randomly choose a movie from the movies list and store it in random_movie.
Let's try it out!

import random

# This function stores all the movies into the list "movies"
movies = ["The Shawshank Redemption", "The Godfather","Pulp Fiction","The Dark Knight","Forrest Gump","Inception","The Matrix","Star Wars: A New Hope","Jurassic Park","The Avengers"]
# This function randomly chooses a movie from that list
random_movie = random.choice(movies)
random_movie
The Dark Knight

Conclusion - The Random Universe Awaits!

Great job! The random library is your gateway to injecting a dash of unpredictability and excitement into your Python projects. Explore with curiosity and let the magic of randomness guide your path to discovery and innovation!

You can read more about the random library from the Python documentation here.