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?

Justin
  • 547
  • 3
  • 7
  • 15
  • 3
    You should use [`random.shuffle`](http://stackoverflow.com/questions/473973/shuffle-an-array-with-python) instead. – Blorgbeard Mar 04 '14 at 00:18

5 Answers5

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)
Óscar López
  • 232,561
  • 37
  • 312
  • 386
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.

turnt
  • 3,235
  • 5
  • 23
  • 39
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())
mwaskom
  • 46,693
  • 16
  • 125
  • 127
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
Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
0

To explicitly state blogbeards suggestion,

>>>import random
>>>random.shuffle(words)
>>>print(*words)
Guy
  • 604
  • 5
  • 21