David Watson
David Watson

Reputation: 3432

Python function or syntactic sugar to return all elements of a generator expression?

Given a (finite) generator expression, I would like to make a single function call that returns all elements of the generator expression.

>>> a = (i for i in range(1,101))
>>> a
<generator object <genexpr> at 0x101873460>
>>> a.next()
1
>>> a.next()
2

In other words, I would like to avoid loops like:

for i in a:
    print i

and instead have a syntactic sugar for the loop:

a.all() # or the like

I looked at itertools but it wasn't clear to me that such a thing exists.

Upvotes: 0

Views: 785

Answers (2)

Mentos
Mentos

Reputation: 170

I think it is the best solution.

a = [i for i in range(1, 101)]
print a
[1, 2, 3, ..., 100]

Upvotes: 0

sshashank124
sshashank124

Reputation: 32197

You can just create a list out of it as:

list(a)

Example

a = (i for i in range(1,101))

print list(a)
[1, 2, 3, ..., 100]

Infact, since in this case you are getting the items into a list, you can also use list comprehension:

a = list(range(1, 101))

Now, a is a list instead of a generator object.

Upvotes: 4

Related Questions