Exercise 8.1
(a) Iteration Illustrated
Create the following list:
a = [1,9,4,25,16]
Manually iterate over this list. Call __iter__()
to get an iterator and
call the next()
method to obtain successive elements.
>>> i = a.__iter__()
>>> i
<listiterator object at 0x64c10>
>>> i.next()
1
>>> i.next()
9
>>> i.next()
4
>>> i.next()
25
>>> i.next()
16
>>> i.next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>>
The next()
built-in function is just a shortcut for calling
the next()
method of an iterator. Try using it on a file:
>>> f = open('Data/portfolio.csv')
>>> next(f)
'name,shares,price\n'
>>> next(f)
'"AA",100,32.20\n'
>>> next(f)
'"IBM",50,91.10\n'
>>>
Keep calling next(f)
until you reach the end of the
file. Watch what happens.
(b) Supporting Iteration
On occasion, you might want to make one of your own objects support
iteration—especially if your object simply wraps around an existing
list or other iterable. Make a file portfolio.py
and put the
following class in it.
# portfolio.py
import stock
class Portfolio(object):
def __init__(self,filename):
self.holdings = stock.read_portfolio(filename)
def cost(self):
return sum([s.shares*s.price for s in self.holdings])
Notice that the class does not support iteration:
>>> from portfolio import Portfolio
>>> port = Portfolio('Data/portfolio.csv')
>>> for s in port:
print s
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'Portfolio' object is not iterable
>>>
Modify modify the class so that you can iterate over the contents of the portfolio like this:
>>> port = Portfolio('Data/portfolio.csv')
>>> for s in port:
print s
Stock('AA',100,32.20)
Stock('IBM',50,91.10)
Stock('CAT',150,83.44)
Stock('MSFT',200,51.23)
Stock('GE',95,40.37)
Stock('MSFT',50,65.10)
Stock('IBM',100,70.44)
>>>