Random choice function adds invinsible "0"?

Question:

I wanted to define a function that gets me the set amount of keys in a dictionary and puts it in a list.
The function though adds a "0" to the list, which is not a key and also exceeds the set amount?
I tried the code in 2 different editors (VS Code and Thonny), both did this in like 40% of the time…

The Code:

import random

def random_card(times):
    chosen_card = []
    for t in range(times):
        chosen_card += random.choice(list(cards))
    return chosen_card

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
        }

player_cards = random_card(2)
pc_cards = random_card(2)

print(f"Your cards: {player_cards}nDealer cards: {pc_cards}")

print(list(cards))

Outputs with the "0":

Your cards: ['8', '1', '0']
Dealer cards: ['9', '1', '0']
['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']

Your cards: ['Q', '1', '0']
Dealer cards: ['7', '1', '0']
['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']

Your cards: ['J', '1', '0']
Dealer cards: ['Q', '4']
['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
Asked By: sp14shb3

||

Answers:

This can all be fixed if you use the choices function from the random module instead. That is, simply do the following

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
        }

player_cards = random.choices(list(cards),2)
pc_cards = random.choices(list(cards),2)
Answered By: Ben Grossmann

Problem lies here

chosen_card += random.choice(list(cards))

using += cause problems for any string of length greater than 1, in your case it is 10. Consider following simple examples

cards = []
cards += "7"
print(cards) # ['7']
cards += "10"
print(cards) # ['7', '1', '0']

It did add 1 then 0 rather than 10. If you have to use += AT ANY PRICE then encase added value in list, namely

cards = []
cards += ["10"]
print(cards) # ['10']

otherwise you might use .append which is method altering list inplace, following way

cards = []
cards.append("10")
print(cards) # ['10']
Answered By: Daweo
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.