0

what am i missing here? it's storing every variable as the same card. generate the 'cards' in nested loops, i use a commented out print statement to verify the values are legit one step above appending them to a list, yet when I look at the list later, every 'card' is the same card -the last card made-

def PrintCard(i):
    print i.suit,i.value

class CardClass():
    value = 0
    face = ""
    suit = 0
    slot = 0
    onoff = 0

card = []
decks = 1
x = 1
suits = [0,1,2,3]
values = [2,3,4,5,6,7,8,9,10,10,10,10,11]
n = CardClass()
for d in range(decks):    
    for s in suits:
        n.suit = s
        for v in values:
            n.value = v
            "print s,v, n.suit,n.value"
            card.append(n)


for i in range(len(card)):
    PrintCard(card[i])
Matt McCarthy
  • 89
  • 1
  • 5
  • There are dozens of questions about this problem here. The one I linked to isn't the closest match, but I think it's the "canonical" version of the question, and if you look at the Linked and Related questions on that one, you'll find some that are a more exact match. – abarnert Sep 12 '14 at 05:08
  • Also see [How do I create a multidimensional list](https://docs.python.org/3/faq/programming.html#how-do-i-create-a-multidimensional-list) in the official Python FAQ. – abarnert Sep 12 '14 at 05:11

1 Answers1

2

You created only one card object, and you append that same object to the list many times. Every time you do n.value = v, you are modifying the value of that same object, overwriting the earlier values.

To get different card objects, you need to make a separate instance for every suit/value combo, by moving n = CardClass() inside the inner loop, and set the suit and value only on that one object:

for d in range(decks):    
    for s in suits:
        for v in values:
            n = CardClass()
            n.suit = s
            n.value = v
            "print s,v, n.suit,n.value"
            card.append(n)
BrenBarn
  • 242,874
  • 37
  • 412
  • 384