Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Items being deleted from the wrong list

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading