0

Hello I am a learning python and my question is I have some words in a list I want to randomly select a word using a loop. Every time I run this code below it returns only random single letters like "y n d"

import random
import time

randomwords = ["my", "random", "words"]

for x in randomwords:
    time.sleep(1)
    print(random.choice(x))

how can I make the code return random order of the words like "words" "my" "random"

ruohola
  • 21,987
  • 6
  • 62
  • 97
Jean loriston
  • 39
  • 1
  • 7
  • 1
    Does this answer your question? [Best way to randomize a list of strings in Python](https://stackoverflow.com/questions/1022141/best-way-to-randomize-a-list-of-strings-in-python) – CDJB Feb 05 '20 at 11:34
  • This method, even when corrected can print the same word twice. You need to shuffle the list – clubby789 Feb 05 '20 at 11:39

2 Answers2

2

random.choice(x) will choose from x, and x is an individual word from randomwords.

If you want to choose from randomwords, do it:

for x in randomwords:
    time.sleep(1)
    print(random.choice(randomwords))
ForceBru
  • 43,482
  • 10
  • 63
  • 98
1

You can use random.shuffle for this:

import random
import time

randomwords = ["my", "random", "words"]

for choice in random.shuffle(randomwords):
    time.sleep(1)
    print(choice)

The reason why your original code didn't work the way you wanted, is that x will be assigned to each of the list elements in turn. So on the first cycle x = "my", and then you print a random character from that string with random.choice(x), which will result in either m or y.

ruohola
  • 21,987
  • 6
  • 62
  • 97