PYTHON: Making the element of a list a class attribute of an instance variable

Hi, I’m trying to build an UNO game and I’m in the process of creating the deck. Right now I’m stuck with creating the action cards to then append to the entire deck. This is my code:

#CREATING THE CLASS

class Card:
  def __init__(self, symbol, colour, is_action_card = False, is_wild_card = False):
    self.symbol = symbol
    self.colour = colour
    self.is_action_card = is_action_card
    self.is_wild_card = is_wild_card

  def __repr__(self):
    return "{symbol}, {colour}".format(symbol=self.symbol, colour=self.colour)


colour_list = ["red", "green", "blue", "yellow"]
reverse_card = Card("reverse", "", True)
reverse_cards = []

for colour in colour_list:
  reverse_card.colour = colour
  reverse_cards.append([reverse_card])
print(reverse_cards)
#PRINTS [[reverse, yellow], [reverse, yellow], [reverse, yellow], [reverse, yellow]]

I’m trying to create a loop which will assign each colour inside colour_list to the instance reverse_card as its “colour” attribute, but when I run it I get the result above. What I’m trying to get is [[reverse, red], [reverse, green], [reverse, blue], [reverse, yellow]], what am I missing in my loop?

Any help is very welcome!!! Thank you!!!

Hello there,

I am no expert at python, but this works.

probably some issue with initializing a class object.

Have a nice day!

class Card:
  def __init__(self, symbol, colour, is_action_card = False, is_wild_card = False):
    self.symbol = symbol
    self.colour = colour
    self.is_action_card = is_action_card
    self.is_wild_card = is_wild_card

  def __repr__(self):
    return "{symbol}, {colour}".format(symbol=self.symbol, colour=self.colour)


colour_list = ["red", "green", "blue", "yellow"]
reverse_cards = []

for colour in colour_list:
  reverse_card = Card("reverse", "", True)
  reverse_card.colour = colour
  reverse_cards.append(reverse_card)
print(reverse_cards)
1 Like