0

I stumbled upon a nifty tool in Python, but I can't seem to find what it's called in the community. I've tried searching through list comprehension pages, but nothing I've found mentions this. Here is an example code:

w = 'abc'

x = ['q', 'k'][len(w) == 3]
y = ['q', 'k'][len(w) > 4]

print x
print y

And the output will look like:

k
q

So there's a list, followed by a true/false block. If the code in the block is True, it will print the second item in the list; if False, it will print the first item.

I wanted to learn more about this type of structure, but like I said, I can't seem to find any leads. I was thus wondering if someone could point me in the right direction. And, if you have any information to add, please share!

vaultah
  • 44,105
  • 12
  • 114
  • 143
Krac
  • 29
  • 5
  • 2
    The `True`/`False` is being converted to `1` or `0` and this is being used to subscript into the preceding list, this kind of coding seems a bit pointless to me as it requires more deciphering than a simple `if/else` block – EdChum Aug 25 '16 at 12:19
  • Is the above code working? what is your exact query? are you trying to resolve the code that is not working? or you want to learn more about tool called `niffty` – Smit Aug 25 '16 at 12:20
  • 1
    This is the kind of code someone might have written before `x = 'k' if len(w) == 3 else 'q'` became valid syntax. – chepner Aug 25 '16 at 12:30
  • Thank you EdChum and chepner for the explanations! And thank you vaultah for the link to the other page; very helpful! Exactly what I wanted. – Krac Aug 25 '16 at 12:38

0 Answers0