-5

I have 2 global lists:

hands={}
hand={}

Then I have function inside which I have while loop. Once the hand is full it gets appended to the hands and after that hand should be cleared.

So I tried like this:

if len(hand)==2:
   hands.append(hand)
   hand.clear()

I tried to print the hands while the while loop is running and it's OK - it contains all the appended sub-lists with the appropriate content but once the loop is over - the hands list contains the sub-lists without any content in them. What am I missing?

martineau
  • 119,623
  • 25
  • 170
  • 301
Kurlander
  • 1
  • 1
  • 4
  • 8
    Those are dictionaries, not lists. – mkrieger1 Aug 27 '20 at 18:36
  • You only insert a reference to `hand` into `hands`. You want to insert a copy. – mkrieger1 Aug 27 '20 at 18:37
  • 3
    Mutable types (like `list`) have reference semantics in Python. That means the `hand` inside of `hands` is the *same object* as the one outside. You need to `.copy()` the list if you don't want changes to be shared. – 0x5453 Aug 27 '20 at 18:38
  • What @0x5453 said applies to dictionaries, too, since they're one of the mutable types (and what you have in your question). – martineau Aug 27 '20 at 18:50

1 Answers1

0

First of all use a list not a dictionary .

hands = [] 
hand = [] 

Then while appending hand in hands use this:

hands.append(hand[:])

This should work.

( hand[:] provides a reference to a copy of hand, so even if you clear or change hand, the changes will not appear in hands. Simply appending hand to hands gives hands direct access to hand. As lists are mutable in python the changes will appear in hands).

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459