views:

102

answers:

2

Suppose I have a list that I wish not to return but to yield values from. What is the most Pythonic way to do that?

Here is what I mean. Thanks to some non-lazy computation I have computed the list ['a', 'b', 'c', 'd'], but my code through the project uses lazy computation, so I'd like to yield values from my function instead of returning the whole list.

I currently wrote it as following:

List = ['a', 'b', 'c', 'd']
for item in List:
    yield item

But this doesn't feel Pythonic to me.

Looking forward to some suggestions, thanks.

Boda Cydo.

+1  A: 

You can build a generator by saying

(x for x in List)
jellybean
So I can do `return (x for x in list)`?
bodacydo
Yes. But I don't think it'll save you much effort, since you've already computed the entire list, so why not return it?
jellybean
The built-in iter() does this for you: there is no need for a generator expression, which also has the disadvantage of being slower.
EOL
+6  A: 

Just wrap your list by iter to create a listiterator e.g.

return iter(List)

BUT why you need to do that? you can just return List ?

Anurag Uniyal
Good question. And I have no answer. I will return the whole list. I just thought returning a generator was a good idea because everything in the project used generators (except this place - i get this list from a library that is not lazy).
bodacydo