edA-qa mort-ora-y
edA-qa mort-ora-y

Reputation: 31951

Create list from generator

Is there a shortcut to creating a list from a generator? I'm doing this now:

list_form = [ item for item in some_generator ]

I need to sort the data before iteration, thus can't use the generator directly in my loop.

Upvotes: 3

Views: 974

Answers (3)

Paul Evans
Paul Evans

Reputation: 27577

You can simple use:

list_form = list(some_generator)

Upvotes: 1

Nafiul Islam
Nafiul Islam

Reputation: 82600

You can use list():

l = list(generator)

The blinding proof (yes, I feel dramatic):

>>> from itertools import chain
>>> a = [['1', '2'], ['a']]
>>> gen = chain.from_iterable(a)
>>> gen
<itertools.chain object at 0x027EE3F0>
>>> list(gen)
['1', '2', 'a']

If that was too dramatic (using itertools to prove a simple point):

>>> xrange(10)
xrange(10)
>>> list(xrange(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1125058

Yes, use the list() constructor:

list_form = list(some_generator)

list() takes any iterable and adds its values to a newly created list object.

However, if you need a sorted list, you may as well use sorted() directly:

sorted_form = sorted(some_generator)

Upvotes: 9

Related Questions