Home > Software engineering >  How to understand list comprehension in Python
How to understand list comprehension in Python

Time:08-05

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()

CodePudding user response:

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

CodePudding user response:

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.

CodePudding user response:

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]
  • Related