How to understand list comprehension in Python

Question:

It’s word library from words import words

I chose a random word and I stuck here word_list= [letter if letter in used_letters else '-' for letter in word] I did not understand that.

import random 
from words import words
LIVES=7

def valid_word(words):
    word=random.choice(words)
    while ' ' in word or '_' in word:
        words=random.choice(words)
    return word.upper()

def hangman():
    word=valid_word(words)
    word_letters = set(word)
    used_letters = set()
    
    while len(word_letters) > 0 and LIVES > 0:
        print(f"You have {LIVES} lives left and you have these letters",' '.join(used_letters))

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

        

hangman()
Asked By: codeRunner

||

Answers:

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

is exactly the same as:

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

Same logic, different syntax.

Answered By: JNevill

read it backwards, to a degree:

word_list= []

for letter in word:
    if letter in used_letters:
        word_list.append[letter]
    else:
        word_list.append['-']

I think that coveres it. When it comes to list comprehensions, i dont know how to explain them really, i know it took me a lot of practice to be comfortable with them and to use them. good luck pal

Answered By: Gregory Sky

When I’m reading them, I find it helpful to insert a newline similar to the following:

word_list = [letter 
             if letter in used_letters else '-' 
             for letter in word]
Answered By: user1453863
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.