Hey, can someone explain to me what a python generator is and how to use it?I need to know it to solve a problem.Thanks
http://docs.python.org/2.7/howto/functional.html#generators http://docs.python.org/2.7/reference/simple_stmts.html#the-yield-statement http://docs.python.org/2.7/library/stdtypes.html#generator-types http://docs.python.org/2.7/reference/expressions.html#yield-expressions http://docs.python.org/2.7/howto/functional.html#generator-expressions-and-list-comprehensions
Here's a fibonacci generator. def fib(n): a,b = 0,1 for _ in xrange(n): yield b a,b = b, a+b And a test print fib(10) print list(fib(10)) for i in fib(10): print i, And the output <generator object fib at 0x0298F490> [1, 1, 2, 3, 5, 8, 13, 21, 34, 55] 1 1 2 3 5 8 13 21 34 55
Join our real-time social learning platform and learn together with your friends!