Justin
Justin

Reputation: 577

Python lists not working properly

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?

Upvotes: 2

Views: 653

Answers (5)

mwaskom
mwaskom

Reputation: 48992

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

Upvotes: 1

Guy
Guy

Reputation: 624

To explicitly state blogbeards suggestion,

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

Upvotes: 0

Joran Beasley
Joran Beasley

Reputation: 113940

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

Upvotes: 0

turnt
turnt

Reputation: 3255

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.

Upvotes: 3

Óscar López
Óscar López

Reputation: 235984

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)

Upvotes: 6

Related Questions