The generator method close() is used to force terminate a generator. It will raise a GeneratorExit exception and will end the generator where it was last paused.

If we attempt to call next() on our generator after close() has been called, no result will be produced.

The close() method is used in the following example:

for item in my_generator: if item == 3: my_generator.close()

The close() method is somewhat similar to using the throw() method in that it is the equivalent of using throw() with the GeneratorExit exception raised with it. The following code below is equivalent to the code snippet above.

for item in my_generator: if item == 3: my_generator.throw(GeneratorExit)

You may be wondering in what scenarios we would want to use close() over throw(GeneratorExit). Imagine we are in the middle of executing a for loop. If we were to use throw(), since an exception is raised, the execution of the for loop will also stop. If we used close() instead, the for loop would continue executing.

To practice with this further, we can attempt to use the close() method on our student generator.



We have a collection of 5,000 students. We only want to retrieve information on the first 100 students. Use the close() method to terminate the generator after 100 students.

Sign up to start coding

By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.
Already have an account?