-2

I want to convert a loop-based script containing if, elif and else into a list comprehension but I cannot figure out how to do it.

Here is the script I wrote (it prints the numbers from 1 to 100, but for multiples of 3 it prints 'fizz', for multiples of 5 it prints 'buzz' and for multiples of both 3 and 5 it prints 'fizzbuzz'):

for num in range(1, 101):
    if num % 3 == 0 and num % 5 == 0:
        print('fizzbuzz')
    elif num % 3 == 0:
        print('fizz')
    elif num % 5 ==0:
        print('buzz')
    else:
        print(num)
bonnal-enzo
  • 1,055
  • 8
  • 17
Flahmez
  • 45
  • 1
  • 4

2 Answers2

2

You can't use elif in list comprehension because it's not part of the if-else short expression syntax.

But you can get the same logic with chaining:

if b1:
    a
elif b2:
    b
else:
    c

becomes

a if b1 else b if b2 else c

So this do the trick for you :

[print('fizzbuzz') if num %3 == 0 and num%5 == 0  else print('fizz') if num%3 == 0 else print('buzz') if num%5 ==0 else print(num) for num in range(1, 101)]

Note: it is totally discouraged to use such unreadable list comprehensions in real life projects !

bonnal-enzo
  • 1,055
  • 8
  • 17
  • A pointless list of `None`s vs. a pointless more heavy list of `str`s objects that are just aimed to be printed. About readability: for me list comprehension are maily usefull for one-line readability, because if you have to split it in several lines, you would rather initialize a list of *n* `None`s and fill it with a regular loop because it looks standard and it is faster (slightly but still). – bonnal-enzo Jul 17 '19 at 09:58
  • You should NOT use list comprehension unless you plan to use the resulting list. List comprehension is not just a way to do a one line for loop. At bare minimum two line it with a generator. If you want it in one line than just use `;` though the OP should break out of the mentality that one line of code is better than multiple. – Error - Syntactical Remorse Jul 18 '19 at 13:34
  • I agree with you. But I think the author question was in a study/training context. Maybe an exercice to play with python syntax possibilities or something like that. So for me it does have sense to wonder how to convert some regular loops into list comprehension, even if it's not pythonic or fast or good looking in this specific case. – bonnal-enzo Jul 18 '19 at 13:41
1

List comprehension is not the right tool since you want to do something (print) and not to produce a list.

First, you should replace the "switch" by a function:

def foobar(num):
    if num % 3 == 0 and num % 5 == 0:
        return 'fizzbuzz'
    elif num % 3 == 0:
        return 'fizz'
    elif num % 5 ==0:
        return 'buzz'
    else:
        return str(num) # return a string to have a consistent return type

(You can make a one liner of this function as in @EnzoBnl's answer if you want, but that's not a good idea.). Now, you code looks like:

for num in range(1, 101):
    print(foobar(num))

If you want a list comprehension (a generator here), use:

print("\n".join(foobar(num) for num in range(1, 101)))
jferard
  • 7,212
  • 2
  • 18
  • 32