Search code examples
pythonsetgenerator

How to add generator elements to a set() without a loop?


From this link it says generators aren't initialized like iterables.

How do you add the elements of a generator to a set? Is there a better way than just a for item in generator sort of thing and using setname.add(item)?

The generator is that returned by a cursor.execute("SELECT ...") command to the cursor from a connection to an sqlite3 database.


Solution

  • You could also just do set(gen):

    >>> set(x**2 for x in range(5))
    set([0, 1, 4, 9, 16])
    

    (Note that this creates a new set with just the elements in the generator. You'll need to do something along the lines of unutbu's answer if you want to add the elements to a pre-existing set.)