0

So, whenever I try and remove an element from cards_left['hearts'], it removes the element from all other lists inside of the dictionary, can anyone help me with this?


card_values = list(range(2,11)) + ['j','q','k','a']
card_values_names = list(range(2,11)) + ['jack','queen','king','ace']
suits = ['hearts','spades','diamonds','clubs']
all_cards,cards_left = {},{}
for suit in suits:
    all_cards[str(suit)] = card_values
    cards_left[str(suit)] = card_values
def take_turn():
    random_suit = random.choice(suits)
    random_card = random.choice(cards_left[str(random_suit)])
    
    print(cards_left)

for i in range(5):
    take_turn()

print(cards_left)
Luke101
  • 63,072
  • 85
  • 231
  • 359
magamman
  • 1
  • 2
  • 3
    Try replacing `cards_left[str(suit)] = card_values` with `cards_left[str(suit)] = list(card_values)` and similarly `all_cards[str(suit)] = card_values` with `all_cards[str(suit)] = list(card_values)` – Stef Nov 19 '20 at 00:31
  • 1
    Or this one? [List changes unexpectedly after assignment, how do I clone or copy it to prevent this?](https://stackoverflow.com/questions/2612802/list-changes-unexpectedly-after-assignment-how-do-i-clone-or-copy-it-to-prevent/2612815) – Stef Nov 19 '20 at 00:33
  • Because *there is only one list*. Your dict's contains multiple references to the same object. – juanpa.arrivillaga Nov 19 '20 at 00:37

1 Answers1

1

Your suits are sharing the same copy of the list card_values. You need to make a copy of the list for each assignment. e.g.

for suit in suits:
    all_cards[str(suit)] = card_values[:]
    cards_left[str(suit)] = card_values[:]

niuer
  • 1,589
  • 2
  • 11
  • 14