Search code examples
pythonarraysmultidimensional-arrayplaying-cards

How to exclude one item from an array based on another array's condition (for deck of playing cards)?


I have two arrays one for the card suit suit_list = ["Hearts", "Diamonds", "Clubs", "Spades"] and one for the values value_list = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]

I have written the code to select a card at random.

Based on this, for the random card selected e.g. 2 of Diamonds, I would like to prevent from being selected again.

How can I tackle this approach? My initial thought was to use a conditional approach in nested for loops but it doesn't seem to be working.

Thanks for your help.


Solution

  • Rather than thinking of removing a card from play, why not create the deck, shuffle it, then as you need cards from the deck just take the next card from the array.

    import random
    import itertools
    
    suit_list = ["Hearts", "Diamonds", "Clubs", "Spades"]
    value_list = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]
    
    deck = list(itertools.product(suit_list, value_list))
    random.shuffle(deck)
    
    for card in deck:
        print(card)