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?
You can use the lambda and iter functions to create an empty iterable in Python. Show activity on this post. This can be considered "most pythonic" because this is what python itself uses. Note that technically all answers so far provide iterators ( __iter__ + next ), not iterables (just __iter__ ).
To create an object/class as an iterator you have to implement the methods __iter__() and __next__() to your object. As you have learned in the Python Classes/Objects chapter, all classes have a function called __init__() , which allows you to do some initializing when the object is being created.
Yield is a keyword in Python that is used to return from a function without destroying the states of its local variable and when the function is called, the execution starts from the last yield statement. Any function that contains a yield keyword is termed a generator.
The Yield keyword in Python is similar to a return statement used for returning values or objects in Python. However, there is a slight difference. The yield statement returns a generator object to the one who calls the function which contains yield, instead of simply returning a value.
Yes, there is:
return iter([])
Another solution, in Python 3, is to use the new yield from
syntax:
def empty_gen(): yield from ()
Which is readable, and keep empty_gen
as a generator.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With