Python 3: 15, 17, or 18 characters
mdeitrick's answer is longer in Python 3, which replaces the print statement with a function call (15 chars):
while 1:print()
This remains the shortest I've found in Python 3. However, there are some more-interesting ways of printing in an infinite loop that are only a few characters longer.
print()returnsNone, which != 9, making it an infinite loop; the8is a no-op that substitutes forpass(18 chars):while print()!=9:8iter(print, 9)defines an iterable that returns the output ofprint()until it equals9(which never happens).anyconsumes the input iterable looking for a true value, which never arrives sinceprint()always returnsNone. (You could also usesetto the same effect.)any(iter(print,9))Or, we can consumer the iterable by testing whether it contains
8(17 chars):8in iter(print,9)Or, unpack it using the splat operator:
*_,=iter(print,9)The weirdest way I thought of is to use splat destructuring inside a function call,
function(*iterable). It seems that Python tries to consume the entire iterable before even attempting the function call—even if the function call is bogus. This means that we don't even need a real function, because the type error will only be thrown after the iterable is exhausted (i.e. never):8(*iter(print,9))
- 2.3k
- 1
- 18
- 21