Iterators in Python 2 - Drexel University
Iterators in Python 2 Kurt Schmidt
Intro Comprehensions zip Creating
Iterators in Python 2
Kurt Schmidt
Dept. of Computer Science, Drexel University
September 21, 2021
Overview
Iterators in Python 2 Kurt Schmidt
Intro Comprehensions zip Creating
? An iterator iterates over an iterable object ? Examples of iterable objects:
? str list tuple dict file ? An iterator serves up items one at a time
? Objects can serve up an iterator (often itself) ? Invoked in the for loop
1 l = [1, 2, 3]
2 for i in l :
3
print i
str doesn't have an iter method; the iter() operator sees the getitem (idx) method, builds an iterator.
Built-in Iterators
Iterators in Python 2 Kurt Schmidt
Intro Comprehensions zip Creating
? list, tuple, dict, others, provide an iterator upon asking
? next(...) accesses values, moves the iterator along ? Raises the StopIteration exception when it's done
1 l = [1, 2, 3]
2 it = iter( l )
3 try:
4
while True :
5
print( next( it ))
6
except StopIteration , e :
7
print( "\nAnd , that's all\n" )
Avoiding the StopIteration
Iterators in Python 2 Kurt Schmidt
Intro Comprehensions zip Creating
? There is no hasNext(...) predicate
? Raises the StopIteration exception when it's done ? next( iter [, default] ) will take a default value to
return, rather than raising an exception ? Choose a generic object, used for its unique reference
1 l = [1, 2, 3]
2 END_ITER = object() # just a sentinel reference
3
4 v = next( l, END_ITER )
5 while v is not END_ITER :
6
print( v )
7
v = next( l, END_ITER )
8 print( "\nAnd , that's all\n" )
for-loop calls iter(...)
Iterators in Python 2
Kurt Schmidt
Intro
Comprehensions zip
Creating 1 2 3 4 5
? for i in iterable expects iterable to be iterable ? Class iter( iterable ) ? Takes care of catching StopIteration
l = [1, 2, 3]
for i in l : print( i )
print( "\nAnd , that's all\n" )
1 2 3
And, that's all
................
................
In order to avoid copyright disputes, this page is only a partial summary.
To fulfill the demand for quickly locating and searching documents.
It is intelligent file search solution for home and business.