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?

1
  • Please post a runnable code example. Commented Jul 21, 2013 at 19:18

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.