Skip to content

Instantly share code, notes, and snippets.

@manjuraj
Created February 12, 2012 02:22
Show Gist options
  • Save manjuraj/1805839 to your computer and use it in GitHub Desktop.
Save manjuraj/1805839 to your computer and use it in GitHub Desktop.
Iterators in Python
items = [1, 2, 3]
it = iter(items)
# prints 1
print it.next()
# prints 2
print it.next()
# prints 3
print it.next()
# raise StopIteration
print it.next()
# Iteration Protocol
#
# An inside look at the for statement
# for x in obj:
# # statements
#
# Underneath the covers
# _iter = iter(obj) # Get iterator object
# while 1:
# try:
# x = _iter.next() # Get next item
# except StopIteration: # No more items
# break
# # statements
#
# Any object that supports iter() and next() is said to be "iterable".
# pending -- http://www.dabeaz.com/generators/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment