-2

I have this line of code in a hangman program

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

and it takes the word that was picked and puts '-' in place of the letters that weren't guessed yet.

I just don't understand how the line works. How is there an if statement and a for loop inside a list? What is this if statement doing if letter in used_letters?

If someone could break it down for me I feel like it would make way more sense.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • https://www.tutorialspoint.com/How-does-in-operator-work-on-list-in-Python – Nick ODell Oct 25 '22 at 19:52
  • 5
    This is a [list comprehension](https://www.geeksforgeeks.org/python-list-comprehension/) – Barmar Oct 25 '22 at 19:52
  • 2
    Does this answer your question? [Is there a short contains function for lists?](https://stackoverflow.com/questions/12934190/is-there-a-short-contains-function-for-lists) – Makoto Oct 25 '22 at 19:53
  • Have you tried rewriting the line into something else (such as many lines) to understand how it works? – OneCricketeer Oct 25 '22 at 19:56

1 Answers1

-1

True if True else False => True

True if False else False => False

If you take it apart, your cycle looks something like this:

word_list = []
for letter in word:
    if letter in used_letters:
        word_list.append(letter)
    else:
        word_list.append('-')
nnekkitt
  • 76
  • 7