forked from freeCodeCamp/freeCodeCamp
-
Notifications
You must be signed in to change notification settings - Fork 2
Python Iterators
Quincy Larson edited this page Aug 20, 2016
·
1 revision
Python supports a concept of iteration over containers. This is implemented using two distinct methods; these are used to allow user-defined classes to support iteration.
TODO: Clarify what iteration means and what iterators can be used for.
-
Objects can implement a
__iter__()
method that returns an iterator object to support iteration. -
Iterator objects must implement:
-
__iter__()
: returns the iterator object. -
__next__()
: returns the next object of the container.
-
iterator_object = 'abc'.__iter__()
print(iterator_object)
print(id(iterator_object))
print(id(iterator_object.__iter__())) # Returns the iterator itself.
print(iterator_object.__next__()) # Returns 1st object and advances iterator.
print(iterator_object.__next__()) # Returns 2nd object and advances iterator.
print(iterator_object.__next__()) # Returns 3rd object and advances iterator.
print(iterator_object.__next__()) # Raises StopIteration Exception.
Output :
<str_iterator object at 0x102e196a0>
4343305888
4343305888
a
b
c
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
<ipython-input-1-d466eea8c1b0> in <module>()
6 print(iterator_object.__next__()) # Returns 2nd object and advances iterator.
7 print(iterator_object.__next__()) # Returns 3rd object and advances iterator.
----> 8 print(iterator_object.__next__()) # Raises StopIteration Exception.
StopIteration:
Learn to code and help nonprofits. Join our open source community in 15 seconds at http://freecodecamp.com
Follow our Medium blog
Follow Quincy on Quora
Follow us on Twitter
Like us on Facebook
And be sure to click the "Star" button in the upper right of this page.
New to Free Code Camp?
JS Concepts
JS Language Reference
- arguments
- Array.prototype.filter
- Array.prototype.indexOf
- Array.prototype.map
- Array.prototype.pop
- Array.prototype.push
- Array.prototype.shift
- Array.prototype.slice
- Array.prototype.some
- Array.prototype.toString
- Boolean
- for loop
- for..in loop
- for..of loop
- String.prototype.split
- String.prototype.toLowerCase
- String.prototype.toUpperCase
- undefined
Other Links