Reputation: 31951
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
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
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