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