Adam Lindberg Adam Lindberg - 7 months ago 16
Python Question

What is the simplest way to create an empty iterable using yield in Python?

I was playing around with iterables and more specifically the

yield
operator in Python. While using test driven development to start writing a new iterable, I wondered what is the shortest code that could make this simple test for an iterable to pass:

def test():
for x in my_iterable():
pass


The shortest version I could think of was:

def my_iterable():
for i in []:
yield i


Is it possible to write a simpler, shorter or more beautiful (pythonic) version?

Answer

You can use the lambda and iter functions to create an empty iterable in Python.

my_iterable = lambda: iter(())
Comments