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()
Asked
Active
Viewed 57 times
-1

Yevhen Kuzmovych
- 10,940
- 7
- 28
- 48

Hagop Ghazarian
- 1
- 1
-
You *must* provide a [mcve]. Almost assuredly, though, it's because both variables are referring to *the same object* – juanpa.arrivillaga Jan 30 '21 at 19:35
-
1Why does this have the dictionary tag? – khelwood Jan 30 '21 at 19:41
-
Does [this](https://stackoverflow.com/questions/29785084/changing-one-list-unexpectedly-changes-another-too) answer your question? – Yevhen Kuzmovych Jan 30 '21 at 20:18
-
@YevhenKuzmovych It didn't help. I'm getting the same result. I changed the code to be reproducible. Can you please check if you can help? Thanks. – Hagop Ghazarian Jan 30 '21 at 20:28
-
As per @quamrana's answer and answers in the link I've posted, you need to deep-copy your list when appending. I.E. `self.Hands.append(x[:])` or `self.Hands.append(list(x))` . – Yevhen Kuzmovych Jan 30 '21 at 20:32
-
@YevhenKuzmovych Deep copy worked. Thanks so much. I really appreciate it. – Hagop Ghazarian Jan 30 '21 at 20:41
1 Answers
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
-
Same with me but when I do the same in class form, both Hands and Cards are being appended by the KKK item. I can't understand why for the life of me. – Hagop Ghazarian Jan 30 '21 at 20:10
-
-
I fixed the code to be reproducible. Can you please check if you can help. Thanks. – Hagop Ghazarian Jan 30 '21 at 20:27
-
Deep copy fixed it. Suggestion from @Yevhen Kuzmovych. Thanks so much also. – Hagop Ghazarian Jan 30 '21 at 20:44