dantan04 dantan04 - 1 month ago 33
Python Question

Print a list of words in random order - Python

I have a project to complete from a book which was received as a Christmas present (Python Programming for the Absolute Beginner, Third Edition):

Create a program that prints a list of words in random order. The program should print all the words and not repeat any.

I have created the following code:

import random

words = ["Please", "Help", "Me", "Merry", "Christmas"]

for i in range(len(words)):
random_index = random.randrange(len(words))
print(words[random_index])
del words[random_index]


I'd like to check if this code is the most efficient way of doing so, but there is no forum to check against, rather frustratingly!

Is there a better way of doing this? Cheers

Answer

How about using random.sample:

>>> import random
>>> words = ["Please", "Help", "Me", "Merry", "Christmas"]
>>> random.sample(words, len(words))
['Merry', 'Me', 'Help', 'Please', 'Christmas']

or random.shuffle if it is okay to modify the original list:

>>> random.shuffle(words)
>>> words
['Me', 'Merry', 'Help', 'Please', 'Christmas']
Comments