Search code examples
pythonlistblackjack

Pop element from a list into a list [Python 3.x]


I'm making a BlackJack game in Python, but it doesn't respect my indexation. It pops a random element from all my sublists, not just from one list.

import random

class Deck(object):

    def __init__(self):
        self.deck_of_cards = []
        self.base = []
        for i in range(0, 13):
        troca = {
            0: 'A',
            10: 'J',
            11: 'Q',
            12: 'K'
        }
        if not i in (0, 10, 11, 12):
            self.base.append(i + 1)
        else :
            self.base.append(troca.get(i))

        for i in range(0, 4):
            self.deck_of_cards.append(self.base)


        def random_card(self, quantidade):
            print(self.deck_of_cards)
            for i in range(0, quantidade):
                 self.deck_of_cards[random.randint(0, 3)].pop(random.randint(0, 13))


        print(self.deck_of_cards)

bar = Deck()
bar.random_card(2)

Solution

  • Look at the salient code:

    for i in range(0, 4):
        self.deck_of_cards.append(self.base)
    

    You don't have four separate sublists: you have four references to the same sublist If you want four copies of the original, you have to make those copies. Try this:

    for i in range(0, 4):
        self.deck_of_cards.append(self.base[:])