I saw an interesting solution for a programming exercise on leetcode It's not even about the problem/solution itself, so you can read it up on the link provided if you wish. However a high voted solution is this one liner:
Snippet 1
def fizzBuzz2(n):
return ["Fizz" * (not i%3) + "Buzz" * (not i%5) or str(i) for i in range(1, n+1)]
Snippet 2
def fizzBuzz(n):
out = []
for i in range(1, n+1):
if i % 3 == 0 and i % 5 == 0:
out.append("FizzBuzz")
elif i % 3 == 0:
out.append("Fizz")
elif i % 5 == 0:
out.append("Buzz")
else:
out.append(str(i))
return out
However, I've expected that the list comprehension is going to beat the common loop, but when I've timed it and it wasn't the case. Even doing a dis, Snippet 2 has more instructions.
What is making Snippet 1 slow?