0

I am trying to make sure that my code doesn't pick the same word more than once out of a list of words. I have read that random.shuffle and .pop would work well for this, but I'm not sure how to implement that method. If there is a better way that I am not aware of other than shuffle and pop please also let me know.

Here is my code:

handle = open('dictionary.txt')
words = handle.readlines()
handle.close()
words = [ random.choice(words).upper().strip()  # <-- Does random.shuffle go in this line?
for _ in range(5) ]
print ("The words are:")
print(words)

I tried a few different times to get random.shuffle and .pop to work but it would give me the error:

AttributeError: 'NoneType' object has no attribute 'upper'.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • What you need is `random.sample(words, 5)`. – Selcuk Jan 06 '21 at 02:01
  • Here, in case you want to see how it works with shuffle. Note that shuffle does not return anything, but that is shuffles the list in place. so you can just shuffle it and take the first n elements (or iterate over the new list if you need to) "random.shuffle(words); words = words[:5]" – chrise Jan 06 '21 at 02:12

0 Answers0