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

Question:

The following code

import random

cards = {'A': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '10': 10, 'J': 10, 'Q': 10, 'K': 10}

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

produces this result

>>> random_cards(4)
['A', '4', '1', '0', '3']
>>>

The 1 isn’t present in cards.keys(), and it doesn’t come from the value of the A key. I tested this with setting the value to 100 and it still placed the 1.

Is random.choice broken?
If not, what is broken in my program?

Asked By: user3555181

||

Answers:

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'].

Answered By: BlackBeans
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.