max
max

Reputation: 52373

Creating a container from an iterator

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.

Upvotes: 1

Views: 90

Answers (2)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799560

All iterators are iterable. The definition of "iterable" is that an iterator can be created from it.

>>> list(iter((1, 2, 3)))
[1, 2, 3]

Upvotes: 3

Blckknght
Blckknght

Reputation: 104852

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 list or set constructor, and it should work just fine.

Upvotes: 4

Related Questions