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