Adam Lindberg Adam Lindberg - 6 months ago 11x
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

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():

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?


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

my_iterable = lambda: iter(())