Search code examples
pythonooprandomblackjack

Shuffling a list inside an object in Python


I'm new to python oop and I'm trying to make a blackjack game. I create object called cards and I would like to shuffle the cards in pack in __init__ function, but random.shuffle(self.cards * self.number_of_packs) doesn't work, is there any way to do it inside __init__ function, or do I have to do it outside the Cards object?

class Cards:
    def __init__(self):
        import random
        self.onTable = []
        self.cards = ["2 ♥", "3 ♥", "4 ♥..."]
        self.number_of_packs = random.randint(2, 5)
        self.inPack = random.shuffle(self.cards * self.number_of_packs)


Solution

  • random.shuffle performs the shuffle operation on the list argument - it doesn't return a new list. You need to generate a new list first of all, and then use shuffle to shuffle it:

    new_list = self.number_of_packs * self.cards
    random.shuffle(new_list)
    print(new_list)