0

How could I add the cards I removed to my handlist? The draw removes cards but I don't know how to add those removed cards into a list for hand.

import random

deck = ["sA", "s2", "s3", "s4", "s5", "s6", "s7", "s8", "s9", "s10", "sJ", "sQ",
"sK", "dA", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9", "d10", "dJ",
"dQ", "dK", "cA", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "c9", "c10",
"cJ", "cQ", "cK", "hA", "h2", "h3", "h4", "h5", "h6", "h7", "h8", "h9",
"h10", "hJ", "hQ", "hK"]

def draw():
  if len(deck) == 52:
    random_item_from_deck = random.choice(deck)
    deck.remove(random_item_from_deck)
    random_item_from_deck = random.choice(deck)
    deck.remove(random_item_from_deck)
    random_item_from_deck = random.choice(deck)
    deck.remove(random_item_from_deck)
    random_item_from_deck = random.choice(deck)
    deck.remove(random_item_from_deck)
    random_item_from_deck = random.choice(deck)
    deck.remove(random_item_from_deck)
 

hand=[]
hand.append()


print ("cards in deck : " + str(deck))
draw()
print ("Deck after removal of cards : " + str(deck))
print ("Cards in hand : " + str(hand))
Bubble
  • 1

3 Answers3

2

You're going to a lot of trouble for the concept of "transfer these cards". Shuffle the deck and take 5 cards from the top:

random.shuffle(deck)
player_hand, remaining_deck = deck[:5], deck[5:]

Will that handle your case?

Prune
  • 76,765
  • 14
  • 60
  • 81
0

You can start an empty list and use its .append() method

>>> l = ['a', 'b', 'c']
>>> l.append('d')
>>> l
['a', 'b', 'c', 'd']

For this case, you may also find that a set is practical when you only have one of something because it has convenient methods for membership

>>> s = set(('a', 'b', 'c'))
>>> s.remove('a')
>>> s
{'c', 'b'}
>>> s - set(('a', 'c'))
{'b'}

However, as @Prune notes, shuffling and then slicing the deck may be cleaner!

ti7
  • 16,375
  • 6
  • 40
  • 68
0

since all cards in the deck are unique, you can use the index of it first transfer it to hand and then remove it.

code :

import random

deck = ["sA", "s2", "s3", "s4", "s5", "s6", "s7", "s8", "s9", "s10", "sJ", "sQ",
    "sK", "dA", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9", "d10", "dJ",
    "dQ", "dK", "cA", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "c9", "c10",
    "cJ", "cQ", "cK", "hA", "h2", "h3", "h4", "h5", "h6", "h7", "h8", "h9",
    "h10", "hJ", "hQ", "hK"]

hand = [] # define hand here

def draw():
  if len(deck) == 52:
    for i in range(4): # using a for loop to avoid repetition of statements
      random_item_from_deck = random.choice(deck)
      hand.append(deck[deck.index(random_item_from_deck)])
      deck.remove(random_item_from_deck)
        
print ("cards in deck : " + str(deck))
draw()
print ("Deck after removal of cards : " + str(deck))
print ("Cards in hand : " + str(hand))
prajwal
  • 112
  • 6