Question

import random

words = ["Football" , "Happy" ,"Sad", "Love", "Human"]

for word in words:
    word = random.choice(words)
    print(word)
    words.remove(word)

Why does the above code only print out 3 words instead of all 5? Am I trying to achieve printing the words from wordsin a random order in an incorrect way?

No correct solution

OTHER TIPS

You can't modify a list (by adding or removing elements) while iterating over it, the behaviour is undefined. Here's a possible alternative for what you're doing that doesn't have that problem:

random.shuffle(words)
for word in words:
    print(word)

This is because you are not looping correctly. Try this:

import random

words = ["Football" , "Happy" ,"Sad", "Love", "Human"]

while words:
    word = random.choice(words)
    print(word)
    words.remove(word)

You need to make sure that the list words is not empty because you cannot modify an array whilst iterating over it.

People have mostly explained why you're not getting the behavior you want, but just to throw an alternate solution into the mix using a different idiom:

import random
words = ["Football" , "Happy" ,"Sad", "Love", "Human"]
random.shuffle(words)
while words:
    print(words.pop())

you should not modify a list while iterating over it try

for _ in range(len(words)):
    word = random.choice(words)
    words.remove(word)
    print word

To explicitly state blogbeards suggestion,

>>>import random
>>>random.shuffle(words)
>>>print(*words)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top