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"])

try something like:

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

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

Thanks.

Thanks for giving me another option to resolve this problem.

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]

Thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.