StopIteration error from a generator

Hi. I’m working on the generate_seats() function in Plane Tickets and I’m very confused about something. When I run the tests some pass but a bunch of them fail with a StopIteration error. The tests get what looks like the correct results to me, but some of them are marked as failures because of the error.

I’m new to working with generators but my impression is that it’s getting a StopIteration when yield() has returned the last value isn’t a problem, that it’s expected. I thought that’s how it’s supposed to work, not an error that should cause a test to fail. Am I misunderstanding that?

I know I could use try/except to handle this specific error, but I’m assuming that I shouldn’t need to, since we haven’t covered that yet and it’s not mentioned in the hints.

Here’s my code. I’m sure it could be improved but it seems to get the right results when I run it in a Jupyter notebook.

Thanks.

def generate_seats(number):

    row = 1
    letters = generate_seat_letters(number)

    for seat in range(1, number + 2):
        if row == 13:
            row += 1
            continue
        else:
            letter = next(letters)
            yield (str(row) + letter)
            
            if letter == 'D':
                row += 1

Edit: I ran the tests from the CLI and now I do see one failure besides the StopIteration error.

Generator functions yield values and (usually) eventually return. If you can next() on a generator and it doesn’t yield a value, ie it returns a value, you get a StopIteration exception. Typically you iterate over a generator using for i in generator and the for stops when it gets a StopIteration. If you are going to repeatedly call next() on a generator, you need to either make sure you call it the correct number of times or use a try-except to stop reading from the generator when it runs out of values to yield.

Ok, thanks Isaac.