Max Kim
Max Kim

Reputation: 1124

Function generators Python

I was trying to implement a function generator to be used n times. My idea was to create a generator object, then assign that object to another variable and call the re-assigned variable as the function, example:

def generator:
   [...]
   yield ...

for x in xrange(10):
   function = generator
   print function(50)

When I call the print function, I observe that function(50) was not called. Instead the output is: <generator object...>. I was trying to use this function 10 times by assigning it to a generator function, and using this new variable as the generator function.

How can I correct this?

Upvotes: 2

Views: 425

Answers (2)

dansalmo
dansalmo

Reputation: 11704

You can also create generator objects with a generator expression:

>>> (i for i in range(10, 15))
<generator object <genexpr> at 0x0258AF80>
>>> list(i for i in range(10, 15))
[10, 11, 12, 13, 14]
>>> n, m = 10, 15
>>> print ('{}\n'*(m-n)).format(*(i for i in range(n, m)))
10
11
12
13
14

Upvotes: 1

Sukrit Kalra
Sukrit Kalra

Reputation: 34531

Generator Functions return generator objects. You need to do list(gen) to convert them into a list or just iterate over them.

>>> def testFunc(num):
        for i in range(10, num):
            yield i


>>> testFunc(15)
<generator object testFunc at 0x02A18170>
>>> list(testFunc(15))
[10, 11, 12, 13, 14]
>>> for elem in testFunc(15):
        print elem


10
11
12
13
14

This question explains more about it: The Python yield keyword explained

Upvotes: 5

Related Questions