2

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?

Max Kim
  • 1,114
  • 6
  • 15
  • 28

2 Answers2

5

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

Community
  • 1
  • 1
Sukrit Kalra
  • 33,167
  • 7
  • 69
  • 71
1

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
dansalmo
  • 11,506
  • 5
  • 58
  • 53