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

Adam Lindberg picture Adam Lindberg · May 16, 2012 · Viewed 12.3k times · Source

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

James Youngman picture James Youngman · May 16, 2012

Yes, there is:

return iter([])