fbpx

Randomizing Lists

Using the Random object with lists

We saw in module 1 how we can use the Random object to create basic random variables using the randint and randrange functions. There are several other built-in functions to the Random class that allow us to interact with lists in a very efficient way.

The choice Function

If we wanted to pick a random item from a list, we could use the randint function to pick a random index that we reference from the list. For example: 

				
					import random

students = ["Luke", "Leia", "Han", "Chewie", "Lando"]
random_index = randint(0, len(students)-1)
lucky_winner = students[random_index]

print("The lucky winner is", lucky_winner, "!")
				
			

While this is pretty simple and straightforward, there is an even easier way to do this using the built-in choice function rather than randint. The choice function takes in a sequence parameter, which is whatever list, string, or range that we want to randomly select an item from. To simplify the code above, we could instead use:

				
					import random

students = ["Luke", "Leia", "Han", "Chewie", "Lando"]
lucky_winner = random.choice(students)

print("The lucky winner is", lucky_winner, "!")
				
			

The shuffle Function

To mix up the order of elements in a list, we can use the shuffle function. This proves to be very useful when wanting to shuffle a deck of cards, for instance:

				
					import random

my_cards = ["A", "K", "Q", "J", 10, 9, 8, 7, 6, 5, 4, 3, 2]
random.shuffle(my_cards)

print(my_cards) # displays cards in a random order
				
			

The sample function

The sample function works a lot like the choice function, but allows us to choose how many random items we want to choose from a list. This essentially allows us to randomly choose items without replacement. The parameter specifies the size of the sample we want to select. For example:

				
					import random

fruits = ["apple", "banana", "orange", "kiwi", "mango"]

# select two random fruits from the list:
print(random.sample(fruits, 2))
				
			

Replit Practice

Loading...