A better way to rewrite this line?

New to python but have java experience. I was watching a fcc youtube video, and the bolded line in the code snippets below really bothers me. I understand what it does, but I don’t understand the syntax. It is just not logical. Is there another way to rewrite it in a single line? Essentially the line is iterating thru characters in the ‘word’ variable, and if the character is in the ‘used_letters’ list, then add it to a new list, otherwise add ‘-’ to the new list.

word =‘APPLE’
used_letters=[‘A’,‘L’]
word_list = [letter if letter in used_letters else ‘-’ for letter in word]
print(’ '.join(word_list))

A - - L -

Is the list-comprehension way of writing the following:

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

Yes I understand it can be done via a for loop. I was wondering if there is another way to write it in a single line to make it easier to read.

Not really, it could use additional function, to hide away part of it:

word_list = [replace(letter) for letter in word]

Alternatively, to help with readability it might be arranged to not be in a single line:

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

You can add brackets:
word_list = [(letter if letter in used_letters else ‘-’) for letter in word]

That’s just the syntax of list-comprehension and inline if-else. It get’s even weirder if you make nested list-comprehensions… but that’s just the syntax.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.