0

Created a program random words with a list.
When I run the program it will output duplicated items. How do I prevent that. Is there a special command to prevent that?

import random
# random choice from a list
for i in range(6):
      print random.choice (["abacus", "biology", "chemistry", "dog",  elf", "ghost"])
4
Contributors
6
Replies
7
Views
8 Years
Discussion Span
Last Post by dseto200
0

try something like:

import random
wl = ["abacus", "biology", "chemistry", "dog",  "elf", "ghost"]
random.shuffle(wl)
for word in wl:
    print word
0

You could also go:

import random
w1 = ["abacus", "biology", "chemistry", "dog",  "elf", "ghost"]
for f in range(len(w1)):
    w = random.choice(w1)
    w1.remove(w)
    print w
0

Thanks for giving me another option to resolve this problem.

0

Murtan's code is the cleaner code. In paulthom12345's code range(len(w1)) changes as w1 gets shorter, always a dangerous thing to do in a for loop.

If you want to use one more random option, here it is:

import random
w1 = ["abacus", "biology", "chemistry", "dog",  "elf", "ghost"]
# make a list of unique random index values 0 to 5 here
ix_list = random.sample(range(len(w1)), len(w1))
for ix in ix_list:
    print w1[ix]
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.