Home > Software engineering >  Items being deleted from the wrong list
Items being deleted from the wrong list

Time:06-15

I'm coding a deck of cards for a casino project, but have run into a bit of a snag. The way it currently works is that it figures out what game you're playing, then changes the cards variable to be a certain number of decks(multiple of 52 in length). The number is then processed, but that's not relevant. After a certain number of cards are randomly pulled, the deck would be "shuffled(reset) and the game would randomly pick cards again. I excluded the random element because it doesn't affect this problem. I've pinpointed the issue to these lines of code(here shown with a shortened list):

onedeck=[0,1,2,3]
cards=onedeck
cards.remove(3)
print(str(cards))
print(str(onedeck))
#this part should shuffle the deck, but because deck has been altered as well, it doesn't refill the deck
cards=onedeck
cards.remove(3)

When runs, it removes the item from both lists, and the deck can't shuffle. What's causing the item to be deleted from onedeck, and how can I fix it?

CodePudding user response:

onedeck and cards are same instance. You can check the address of the variable with id function.

onedeck = [0, 1, 2, 3]
cards = onedeck
print(hex(id(onedeck) == hex(id(cards)))  # True

You should make new instance as the comment said.

onedeck = [0, 1, 2, 3]
cards = onedeck[:]
cards_new = onedeck.copy()
print(hex(id(onedeck) == hex(id(cards)))  # False
print(hex(id(onedeck) == hex(id(cards_new)))  # False

CodePudding user response:

When you assign variables like cards=onedeck if you change cards, one deck will change and vice versa. So use .copy()

onedeck=[0,1,2,3]
cards=onedeck.copy()
  • Related