Joseph Smith
Joseph Smith

Reputation: 138

How to reference unnamed variable within list comprehension?

This block of code gives the correct output however the expression to generate the replacements for numbers is inefficient as it repeats the same expression twice. Is there a way to make this more concise by not repeating the phrase?

Code:

numphrase = {3: "three", 5: "five"}
result = [''.join([numphrase.get(key) for key in numphrase if not num % key])
          if ''.join([numphrase.get(key) for key in numphrase if not num % key]) else
          num for num in range(101)]
print(*result, sep="\n")

Output:

threefive
1
2
three
4
five
...

Upvotes: 0

Views: 109

Answers (1)

khelwood
khelwood

Reputation: 59146

There's an easier way to write x if x else y in Python, and that's x or y.

So you can write your comprehension as

result = [''.join([numphrase.get(key) for key in numphrase if not num % key]) or num
          for num in range(101)]

Upvotes: 3

Related Questions