In the examples below, resp.results is an iterator.
Version1 :
items = []
for result in resp.results:
item = process(result)
items.append(item)
return iter(items)
Version 2:
for result in resp.results:
yield process(result)
Is returning iter(items) in Version 1 any better/worse in terms of performance/memory savings than simply returning items?
In the “Python Cookbook,” Alex says the explicit iter() is “more flexible but less often used,” but what are the pros/cons of returning iter(items) vs yield as in Version 2?
Also, what are the best ways to unittest an iterator and/or yield? — you can’t do len(results) to check the size of the list?
It’s easy to turn an iterator or generator back into a list if you need it:
Or as kindly pointed out in the comments, an even simpler method: