0

I'm trying to get my head around list comprehension at the moment, and trying to build a blackkack game using as much of it as possible. Im stuck at this particular point:

   elif card == (char for char in ["K", "J", "Q"]):
        print("Detected facecard")

I understand it would possibly be easier to use a dictionary or some alternative method, or even just expand the loop out, but I'm specifically trying to understand why this wont work.

printing char for char in .... yields the object type rather than the objects.

Any suggestions? Thanks in advance

Jkind9
  • 742
  • 7
  • 24

2 Answers2

3

What vurmux commented is the proper way to do it, but here's why what you did won't work:

(char for char in ["K", "J", "Q"]) is a generator, and so what's actually happening is that python is comparing card to that generator, which will always be false.

>> x = (char for char in ["K", "Q", "J"])
>> print(x)
<generator object <genexpr> at 0x7f10752d4410>
Calvin Godfrey
  • 2,171
  • 1
  • 11
  • 27
  • Yeah I understood that, just couldnt get why it was producing a generator – Jkind9 Jun 20 '19 at 15:08
  • 1
    That's what the paranthesis `()` around the statement does. If instead you did `[char for char in ["K", "Q", "J"]]`, it would redudantly generate the list `["K", "Q", "J"]`. – Calvin Godfrey Jun 20 '19 at 15:09
  • Thats the exact answer I was looking for. Thank you very much. – Jkind9 Jun 20 '19 at 15:13
1

(char for char in ["K", "J", "Q"]) constructs the generator:

<generator object <genexpr> at 0x7f97e9f8f200>

So you are trying to compare a card (I think it is not a generator :) ) with generator. It always will be False. You can just check that card is in ["K", "J", "Q"]:

elif card in ['K', 'J', 'Q']:

vurmux
  • 9,420
  • 3
  • 25
  • 45