[Tutor] Need help with generators....

Alan Gauld alan.gauld at btinternet.com
Sat Feb 15 19:37:07 CET 2014


On 15/02/14 13:35, Bunny Sehgal wrote:
> I am doing "Building Skills in Python". In the Generator Function
> example at

I assume you are talking about this one:

spins = [('red', '18'), ('black', '13'), ('red', '7'),
     ('red', '5'), ('black', '13'), ('red', '25'),
     ('red', '9'), ('black', '26'), ('black', '15'),
     ('black', '20'), ('black', '31'), ('red', '3')]

def countReds( aList ):
     count= 0
     for color,number in aList:
         if color == 'black':
             yield count
             count= 0
         else:
             count += 1
     yield count

gaps= [ gap for gap in countReds(spins) ]
print gaps


> what i understood is as follows:>
> 1)First it makes count = 0
> 2)then it goes straight in for loop
> 3)Since the first color is red, it goes in else block and increment
> count to 1 and stop execution.

What makes you think it stops?
It carries on to the next iteration which is black and so enters the if 
block which yields the count which will be 1.

> 4)Now its next method is called using list comprehension, and it resumes
> its execution and yield its first value i.e. 1.Note that the yield
> statement is outside the for loop.

Not quite,
Next time round it carries on from the yield so sets count back
to zero and fetches the next two tuples before hitting another
black. So this time it yields 2.

Once the tuples are exhausted it yields the final count,
which should be 1

> 5)Now there is no further yield statement which can stop execution of
> countreds() function.So it raises StopExecution exception
>
> But this is not what is happening..... why?

Your understanding was flawed. Assuming I've pasted the correct code 
listing... But there is an explanation right under the listing on the 
page. Assuming you read it, which bit of that did you not understand?

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list