Secrets: removing generated variables from a previously defined list?

Viewed 41

I’m using secrets to take two random variables from a previously defined list. I need to do this twice in succession. The second time, I need the program to select from the same list, except selecting the two that were returned in the first instance.

num_to_select = 2
unassigned_cards = [2,3,4,5,6,7,8,9,10,10,10,10,'ACE']
draw_cards = 4*unassigned_cards
dealers_cards = secure_random.sample(draw_cards, num_to_select)
draw_cards.remove(dealers_cards)()
players_cards = secure_random.sample(draw_cards, num_to_select)

This error message appears, understandably, because I’ve asked it to remove objects that are not present in the original list.

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-2-0d34b9c572c9> in <module>
      1 dealers_cards = secure_random.sample(draw_cards, num_to_select)
----> 2 draw_cards.remove(dealers_cards)()
      3 players_cards = secure_random.sample(draw_cards, num_to_select)
      4 
      5 print('Dealer drew', dealers_cards,'for a total of', sum(dealers_cards))

ValueError: list.remove(x): x not in list

For clarification, this is for a game of playing cards, so I multiplied the list by 4 in the third line of code to represent four suits, so removing the “dealer’s cards” from the list should only reduce the likelihood of drawing a particular number, not make it completely impossible.

Please explain where I’ve gone wrong here.

1 Answers

Ok, so the problem here is that sample returns a list with (in your case) 2 values, so you need to do the next:

dealers_cards = draw_cards[randint(0, len(draw_cards)-1)]
draw_cards.remove(dealers_cards)

Here, you are taking one random card from the list and then removing it, if you want to remove 2 cards you can do it with a for loop. It will look like this:

for _ in range(2):
    dealers_card = draw_cards[randint(0, len(draw_cards)-1)]
    print(dealers_card)
    draw_cards.remove(dealers_card)
Related