Skip to content

Instantly share code, notes, and snippets.

@pavdmyt
Created August 29, 2016 15:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pavdmyt/645ce3dbd313290553944384981c918f to your computer and use it in GitHub Desktop.
Save pavdmyt/645ce3dbd313290553944384981c918f to your computer and use it in GitHub Desktop.
Some implementations of infinite / endless for loops in Python.
"""
Some implementations of infinite / endless for loops in Python.
No practical applications, just pure theoretical interest :)
C/C++ example:
for (;;) {}
src: https://stackoverflow.com/questions/5737196/an-expression-for-an-infinite-generator
"""
import itertools
def infinite_for_loop1():
# iter(collection) -> iterator
# iter(callable, sentinel) -> iterator
#
# Get an iterator from an object. In the first form, the argument must
# supply its own iterator, or be a sequence.
# In the second form, the callable is called until it returns the sentinel.
for _ in iter(int, 1):
pass
def infinite_for_loop2():
# Same as `infinite_for_loop1`
for _ in iter(lambda: 0, 1):
pass
#
# itertools examples
#
def infinite_for_loop3():
# count(start=0, step=1) --> count object
#
# Return a count object whose .next() method returns consecutive values.
# Equivalent to:
#
# def count(firstval=0, step=1):
# x = firstval
# while 1:
# yield x
# x += step
for _ in itertools.count():
pass
def infinite_for_loop4():
# cycle(iterable) --> cycle object
# Return elements from the iterable until it is exhausted.
# Then repeat the sequence indefinitely.
for _ in itertools.cycle(range(1)):
pass
def infinite_for_loop5():
# repeat(object [,times]) -> create an iterator which returns the object
# for the specified number of times. If not specified, returns the object
# endlessly.
for _ in itertools.repeat(0):
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment