0

I am trying to build a card game hand simulator. I want to be able to shuffle a list of cards (import random I assume) and then remove cards off the top of the deck and put them into my hand. I want to be able to draw as long as I like.

The PROBLEM is that when I use .pop() to do this, it will remove elements from a randomized list for a few lines, but then eventually stop and then just leave 2 items left in the list. When I look up the documentation, it says .pop() by default removes the item at position 0, so I don't know why it doesn't just continue.

Right now I am trying to use the .pop() method. I am new to python so there may be a better way, I just don't know if there could be a better method. Regardless, I am trying to understand why .pop() didn't solve this problem and the documentation isn't exactly helping.

    '''the for-loop is supposed to shuffle my cards, and then keep plucking one off of the top until there are no more cards in the deck'''

import random
hand = [1,2,3,4,5]
random.shuffle(hand)
for i in hand:
    card = hand.pop(0)
    print(card)
    print(hand)

What I actually get: 1 [4, 5, 3, 2] 4 [5, 3, 2] 5 [3, 2]

What I would LIKE to get: 1 [4, 5, 3, 2] 4 [5, 3, 2] 5 [3, 2] 3 [2] 2 []

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
manski
  • 131
  • 1
  • 10

1 Answers1

2

General explanation:

You're modifying a list at the same time you're iterating over its contents. Bad things happen when you do that.

Slightly more technical explanation:

The for loop for i in hand only evaluates hand once, at the start of the loop . But each time through the loop you're removing items from the list, so the results of the for loop are now out of sync with the current state of the list.

Try this instead:

import random
hand = [1,2,3,4,5]
random.shuffle(hand)
while hand:
    card = hand.pop(0)
    print(card)
    print(hand)
John Gordon
  • 29,573
  • 7
  • 33
  • 58
  • Thanks that worked well. I still don't always know when to use a for-loop vs a while-loop but I guess this was just a learning experience. – manski May 10 '19 at 20:39