Python for Beginners task

I was making the hangman minigame from the beginners pythjon project webpage - where I was struggling to print the correctly guessed letters in order, then print that order with ‘blank’ spaces onto the terminal- so I watched the video tutorial (The bit I am stuck with -starts at about 32:05- or the beginning of the tutorial for the minigame at around 24:45 )
link:

https://www.youtube.com/watch?v=8ext9G7xspg&t=621s)

The line I can not comprehend:

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

What is ‘letter’ (was never stated in my or the hosts code as a variable) and how does it know how to use it and how does it actually utilise it? How does it know which of the letters in ‘used_letters’ are in the word?

This is a list comprehension, which is a bit like a for loop with backwards syntax

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

You can imagine an equivalent for loop:

for letter in word:
    if letter in used_letters:
        word_list.append(letter)
    else:
        word_list.append('-')
1 Like

Thank you, the part I don’t understand is how the system knows what order to put the letters in, not just in the order that they have been inputted since .append() would add to the end?

Not sure the order list comprehension adds to the list, it may not be the same as append() although I think it is. It was just an example, append() isn’t necessarily the exact same effect.

You can test this out.

If you start with the first and keep taking the next letter and add it to the end, it will be the same order, correct?

word = "abc"
neword = ""
word = "bc"
neword = "a"
word = "c"
neword = "ab"
word = ""
neword = "abc"

Anyway you should test this out for yourself with simple tests, it’s the best way to learn.