Python generator


/ Published in: Python
Save to your folder(s)



Copy this code and paste it in your HTML
  1. def generate_ints(N):
  2. for i in range(N):
  3. yield i
  4.  
  5.  
  6. >>> gen = generate_ints(3)
  7. >>> gen
  8. <generator object at 0x8117f90>
  9. >>> gen.next()
  10. 0
  11. >>> gen.next()
  12. 1
  13. >>> gen.next()
  14. 2
  15. >>> gen.next()
  16. Traceback (most recent call last):
  17. File "stdin", line 1, in ?
  18. File "stdin", line 2, in generate_ints
  19. StopIteration
  20.  
  21.  
  22. # another option:
  23. a, b, c = generate_ints(3)
  24.  
  25. # or..
  26. list_of_three = list(generate_ints(3))

URL: http://docs.python.org/release/2.3/whatsnew/section-generators.html

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.