Home > Blockchain >  How can I add an item into an exisitng list (Python)
How can I add an item into an exisitng list (Python)

Time:09-01

I try to write a code for a blackjack game. In the case, the player wishes to draw a new card, I want to write a code that randomly picks a card(number) from a list and inserts into the deck of the player. The code I used was the following:

cards = [11,2,3,4,5,6,7,8,9,10,10,10,10]
players_card= random.choices(cards, k=2)

in case the player wants to draw a new one:

 players_card.append(random.choices(cards, k=1))

the result however is:

[6, 3, [x]]

So it inserts me a list instead of a number and so I cannot further calculate with it. Do I need to use another function instead of .append or what kind of logic am I missing?

CodePudding user response:

the fact is that random.choices(cards, k=1) returns a list.

try using:

players_card = players_card   random.choices(cards, k=1)

CodePudding user response:

random.choices returns a list of random elements from an iterable, with replacement

Either use = (to add two lists together):

players_card  = random.choices(cards, k=1)

Or, use random.choice to only get one element:

 players_card.append(random.choice(cards))

CodePudding user response:

random.choices(cards, k=1) returns a list having only one value. You can concatenate the two lists like this

players_card = players_card random.choices(cards, k=1)

OR you could also do

 players_card.append(random.choices(cards, k=1)[0])

CodePudding user response:

players_card.extend(random.choices(cards, k=1))

  • Related