Tuesday 29 May 2012

Iterators


1)   for x in [1,4,5,10]:
...
print x


2) prices = { 'GOOG' : 490.10,
...
'AAPL' : 145.23,
...
'YHOO' : 21.71 }
...
>>> for key in prices:
...
print key


3) s = "Yow!"
>>> for c in s:
...
print c


In all the above for iteration , what is happening ?



items = [1, 4, 5]
>>> it = iter(items)
>>> it.next()
1
>>> it.next()
4
>>> it.next()
5
>>> it.next()
 
this is the underlying steps which are happening .

what does iter(items) do ..... it just returns iterator object ,,, which has inbuilt methods like next , stopiteration , etc ... after printing once , if the list is not empty , next () is exectued , so this process goes on and on , till list is empty , when the stopiteration is executed . 








No comments:

Post a Comment