-1

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?

Klaus D.
  • 13,874
  • 5
  • 41
  • 48
  • 1
    For `k=1` you may also use `choice()` (no `s`) to get a single element, or use `.extend()` to append a list. – Klaus D. Aug 31 '22 at 09:08

4 Answers4

1

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

try using:

players_card = players_card + random.choices(cards, k=1)
Lucas M. Uriarte
  • 2,403
  • 5
  • 19
1

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))
The Thonnu
  • 3,578
  • 2
  • 8
  • 30
1

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

Dinky Arora
  • 106
  • 4
  • Might you please [edit] your post to provide an [explanation](https://meta.stackexchange.com/q/114762) of how it answers the question and differs from other, similar answers? Doing so would greatly improve its long-term value by showing why this is a good solution to the problem. It would also make it more useful to future readers with other, similar questions. Thanks! – dbc Sep 01 '22 at 16:30
0

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])