[Tutor] Random list exercise

lists lists at justuber.com
Thu Sep 9 22:51:38 CEST 2010


Hi tutors,

Still on my Python learning journey! I've just competed an exercise
which asks the student to "Create a program that creates a list of
words in random order. This program should print all the words and not
repeat any." I've printed the list for my own needs. The list
randwords aims to answer the specific request of the exercise author.

If anyone has the inclination and a minute to spare, please run your
eyes over my answer. It works, but is it an OK way to approach the
exercise?

Thanks again :-D

Chris

import random

#LIST
words = ["one", "two", "three", "four", "five", "six", "seven",
"eight", "nine", "ten", "eleven"]
randwords = []

while words: #has entries in it
    wordslen = len(words) #get the length of the list
    index = random.randint(0, wordslen -1) #get a random index
    chosenword = words[index]
    randwords.append(chosenword) #append the random word to a new list
    del words[index] #del the word from the old list

for word in randwords:
    print word # print them


More information about the Tutor mailing list