2
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?

1
  • 3
    You should use random.shuffle instead. Commented Mar 4, 2014 at 0:18

5 Answers 5

6

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)
Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

1

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())

Comments

0

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

Comments

0

To explicitly state blogbeards suggestion,

>>>import random
>>>random.shuffle(words)
>>>print(*words)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.