2

I want to know what letter if letter means in this code.

I have no variable that's called like that, so how can this be valid? And how does this work in general?

word_list = [letter if letter in used_letters else "-" for letter in word]
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • [This answer](https://stackoverflow.com/a/68969401/1405065) in the duplicate question is the one that most clearly spells out what is going on in your code. There's a list comprehension (`[some_expr for some_var in some_sequence]`), and inside of `some_expr`, a ternary expression (`value if condition else other_value`). It can be a bit confusing because list comprehensions can also contain `if` clauses (but not `else`), and because the comprehension and the condition in your ternary both use `in` (for different purposes). – Blckknght Jan 26 '22 at 00:12

2 Answers2

2

You can read about list comprehensions here:

https://www.w3schools.com/python/python_lists_comprehension.asp

Your line of code is the exact same as the following piece (I assume, you have variables named word and used_letters defined somewhere before):

word_list = []

for letter in word:
    if letter in used_letters:
        word_list.append(letter)
    else:
        word_list.append("-")

The first part letter if letter in used letters else "-" is just shorthand if-else and the rest is for the list comprehension, so as you would not need to define letter in the for loop, which I provided above, the same goes for your line: letter variable does not need to be defined before, since it is a for loop variable.

0
word_list = [letter if  letter in used_letters else "-" for letter in word]

Here 'letter if letter' is a variable created for the sake of list comprehension ( it works inside the square brackets i.e. [ ] and we cannot access the value inside this variable outside this brackets )in python so that we can use this variable to filter out if this letter is in the used_letters list.

raiyan22
  • 1,043
  • 10
  • 20