m01
m01

Reputation: 9395

Standard method for returning all elements generated by a generator or iterator

I'm looking for a neat, ideally standard-library-based method or recipe for turning an iterator or generator object into a list containing all the elements that you would get if you iterated over this object. If there are any different solutions regarding Python 2.7 or 3.x I'd also be interested in knowing. Basically, I'm looking for something functionally equivalent to:

def expand(obj):
    result = []
    for o in obj:
        result.append(o)
    return result

I understand that generators and iterators in Python come with lots of benefits, and that this probably shouldn't be used in .py files. However, I do think this has its uses, especially when programming interactively and when using small datasets for testing.

My best answer so far is list comprehension:

In [55]: a=[1,2,3]
In [56]: r=reversed(a)
In [57]: r
Out[57]: <listreverseiterator at 0x101f51a10>

In [58]: [x for x in r]
Out[58]: [3, 2, 1]

In [59]: def f(x):
   ....:     while x > 0:
   ....:         x-=1
   ....:         yield x
   ....:         

In [60]: [x for x in f(4)]
Out[60]: [3, 2, 1, 0]

I've tried searching Google and StackOverflow without finding anything obvious, and I've checked the itertools and functools docs - most of my attempts based on those just result in more objects. I also had a quick look at IPython magicks, but didn't notice anything obvious there.

Upvotes: 1

Views: 62

Answers (1)

ThiefMaster
ThiefMaster

Reputation: 318748

There is a very simple solution for this: list(the_iterator)

Upvotes: 9

Related Questions