-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,165
  • 9
  • 19
Flahmez
  • 45
  • 1
  • 5

2 Answers2

4

elif is not part of the if-else short-hand, aka if else conditional operator, but you can achieve the same logic by chaining these operators, for example:

if A:
    v = a
elif B:
    v = b
else:
    v = c

turns into

v = a if A else b if B else c

And you can use a conditional operator expression in your list comprehension:

[a if A else b if B else c for something in someiterator]

Note that things can become unreadable quite quickly, for example this may not be recommended in your example:

['fizzbuzz' if num%3 == 0 and num%5 == 0  else 'fizz' if num%3 == 0 else 'buzz' if num%5 == 0 else num for num in range(1, 101)]
bonnal-enzo
  • 1,165
  • 9
  • 19
  • 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
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,835
  • 2
  • 22
  • 35