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

random.choice appears to sometimes return keys that are not there

output:  When random.choice adds a '1' from the keys, it will follow it up with a '0'

When I run this code it works as intended about 90% of the time. Then out of the blue it will inject a [‘1’, ‘0’]. The ‘1’ is not coming from the value of the ‘A’ key. I tested this with setting the value to 100 and it still placed the ‘1’.

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 :

Your error stems from the fact that, to add to a list, you don’t use +=, but append. The correct code is:

def random_cards(n):
    dealt_cards = []
    for _ in range(n):
        dealt_cards.append(random.choice(list(cards.keys())))
    print(dealt_cards)

This is because addition with lists is defined only with iterables, which are converted to a list, then the two lists are concatenated. That is, ['c'] + 'ab' == ['c'] + list('ab') == ['c'] + ['a', 'b'] == ['c', 'a', 'b'].

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