Why doesn't my code put cards into specific hands?

Viewed 30

I'm trying to create an interface with Python 3 on which to play a variety of card games. At the moment I've been making classes for cards, decks, players and "tables" and I'm having a small problem with the latter.

When writing my .deal() method to deal cards to the players at the table, I loop through players, draw the end card in the list of cards contained in the deck, removed it from the deck and assign it to the hand of the player in the loop. Seems simple enough? However, what actually happens is that all of the cards dealt go to all of the players, and I just can't see why? Could anyone help me? I'll put my code below.

for player in self.players:
    card = self.deck.cards[-1]
    self.deck.cards.remove(card)
    player.hand.append(card)
1 Answers

First of all, as stated in comments we are lacking a reproductible example. I will still allow myself to suggest something for your code. you could merge those two lines :

card = self.deck.cards[-1]
self.deck.cards.remove(card)

into one like this :

card = self.deck.cards.pop()

In case you are not familiar with the pop function, when applied to list, it removes the last value when no argument is given, else removes the argument's position in the list (therefore must follow list access elements rules). And you can retrieve the removed elements into a variable or not.

For example, you could simply turn :

self.deck.cards.remove(card)

into

self.deck.cards.pop()

and it would be perfectly valid.

Related