-3

I found some Python code of a hangman game. I came accross the following line of code and I'm unable to make any sense of it.

# here's the initial values of the variables
guessWord = random.choice(listOfWords)
blanks = "-" * len(guessWord)
alreadyGuessed = set()

# This is the line I fail to understand:
blanks = "".join([char if char in alreadyGuessed else "-" for char in guessWord])

I would be glad if you explain it's use.

moooeeeep
  • 31,622
  • 22
  • 98
  • 187

1 Answers1

0

This is called the conditional expression.

It is a one liner, for example:

l = [1,2,3,4]
j = [1,3]

res = []
for i in l:
  if i in j:
    res.append(i)
  else:
    res.append(None)

You can just write:

res = [i if i in j else None for i in l]
DevLounge
  • 8,313
  • 3
  • 31
  • 44
  • 3
    Actually, it is called a [conditional expression](https://docs.python.org/3/reference/expressions.html#conditional-expressions). "Ternary operator" just means an operator that takes three operands. –  Nov 06 '14 at 18:04
  • It is one of several ternary operators. Python only has one at the moment, but the SQL `... BETWEEN ... AND ...` operator is another. This specific one is called a *conditional expression*. – Martijn Pieters Nov 06 '14 at 18:08
  • Just saw your comments, agreed. I was editing my answer, as it was really short. – DevLounge Nov 06 '14 at 18:12
  • Maybe there's an error. Shouldn't it rather be `res = [i if i in j else None for i in l]` ? – moooeeeep Nov 06 '14 at 19:30
  • No, not in this example, as I wanted to put None if i is not in j. There could be tons of other examples, I just created this one... – DevLounge Nov 06 '14 at 19:39
  • It is called a conditional expression, *full stop*. It is a *type* of ternary operator, and it is the `else` part that makes it a ternary operator. There is no binary version of the conditional expression; what would it produce if the `if` statement wasn't true? Remember, operators *always* have output. – Martijn Pieters Nov 07 '14 at 10:21
  • @iCodez "ternary operator" usually refers to _the_ only ternary operator that is present in most programming languages, the conditional operator. – John Dvorak Nov 07 '14 at 10:23
  • Indeed! Thanks, corrected the syntax order in the expression – DevLounge Nov 08 '14 at 18:17