I want to create a set, list, etc. from an iterator. Unfortunately, their constructors require an iterable rather than an iterator. I don’t want to create an iterable that will be discarded shortly.
Of course, I could simply use list or set comprehension, which can do precisely what I want (and more). However, the syntax for them is idiosyncratic. So when I tried to write a function:
def create_from_gen(container_type, generator):
return container_type(generator)
I got stuck. For user-defined containers, I can of course define my own constructors; for library and built-in types I have no choice. I could check for list and set, and use the special syntax I suppose, but that’s ugly.
An iterator is also an iterable object. It should always have an
__iter__method that returns itself. This is part of the specification for iterators in Python.So just pass your iterator to the
listorsetconstructor, and it should work just fine.