Posted By

magicrebirth on 01/10/11


Tagged

python generator


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

kristi


Python generator


 / Published in: Python
 

URL: http://docs.python.org/release/2.3/whatsnew/section-generators.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))

Report this snippet  

You need to login to post a comment.