Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 515
Adam Lindberg Avatar asked May 16 '12 15:05

Adam Lindberg


People also ask

How do you make an empty iterator in Python?

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__ ).

How do you create an iterable in Python?

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.

How do you use the yield function in Python?

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.

How do you find the yield value in Python?

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.


2 Answers

Yes, there is:

return iter([]) 
like image 145
James Youngman Avatar answered Sep 21 '22 23:09

James Youngman


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.

like image 23
aluriak Avatar answered Sep 20 '22 23:09

aluriak