-1
class PokerGame:
    def __init__(self):
        self.Cards = [['A', 'Q'], ['K', '10']]
        self.Hands = []


    def Play(self):
        print(self.Hands) # []
        print(self.Cards) # [['A', 'Q'], ['K', '10']]
        for x in self.Cards:
            self.Hands.append(x) 
        print(self.Hands) # [['A', 'Q'], ['K', '10']]
        print(self.Cards) # [['A', 'Q'], ['K', '10']]
        self.Hands[0].append("KKK")
        print(self.Hands) # [['A', 'Q', 'KKK'], ['K', '10']]
        print(self.Cards) # [['A', 'Q', 'KKK'], ['K', '10']]???

b = PokerGame()
b.Play()
Yevhen Kuzmovych
  • 10,940
  • 7
  • 28
  • 48

1 Answers1

1

This is my reproduction of the problem:

Cards = [['10S', '9S'], ['5H', 'JD']]
Hands = []
for x in Cards:
    Hands.append(x)
print(Hands) # -  ([['10S', '9S'], ['5H', 'JD']])
print(Cards) # - ([['10S', '9S'], ['5H', 'JD']])
Hands[0].append("KKK")
print(Hands) # - [['10S', '9S', 'KKK'], ['5H', 'JD']]
print(Cards) # - [['10S', '9S', 'KKK'], ['5H', 'JD']] ????

Its simply that: Hands.append(x) is not copying anything, its just adding references.

Compare the above to the below:

Cards = [['10S', '9S'], ['5H', 'JD']]
Hands = []
for x in Cards:
    Hands.append(x[:])   # Here is a copy
print(Hands) # -  ([['10S', '9S'], ['5H', 'JD']])
print(Cards) # - ([['10S', '9S'], ['5H', 'JD']])
Hands[0].append("KKK")
print(Hands) # - [['10S', '9S', 'KKK'], ['5H', 'JD']]
print(Cards) # - [['10S', '9S'], ['5H', 'JD']]
quamrana
  • 37,849
  • 12
  • 53
  • 71