How to get a single element from a generator in Python?

In this tutorial, you will learn how to get a single element from a generator in Python.

You must be familiar with Python functions and their uses. However, do you know what exactly a generator function is?
A generator function is basically a function that can return multiple values, by using the yield keyword instead of the return keyword. It is of great use when you want to produce a sequence of values instead of a single value.
To read more on Python generators, click How to use a generator in Python with examples

Using next(generator)

The generator functions, on execution, do not really execute the code. Instead, they return an iterator, called as a generator.

def eg_generator_func():
    yield "a"
    yield "b"
    yield "c"
result=eg_generator_func()
print(result)
<generator object eg_generator_func at 0x00000279744DB6C8>

The generator thus got will return the value against the yield keyword, each time it is called using the generator’s next() method. You can observe the execution of the same as follows.

def eg_generator_func():
    yield "a"
    yield "b"
    yield "c"
generator_obj=eg_generator_func()
res=next(generator_obj)
print(res)
res=next(generator_obj)
print(res)
res=next(generator_obj)
print(res)
a
b
c

Note:

  1. The generator exits by calling the StopIteration.
  2. You cannot use the return keyword inside a generator. This is because the yield keyword pauses the execution and returns the value. But, it maintains the internal state as it is.
    However, the return keyword, after returning the value terminates the execution of the function. The same is shown below:
def eg_generator_func():
    yield "a"
    yield "b"
    return
    yield "c"
generator_obj=eg_generator_func()
res=next(generator_obj)
print(res)
res=next(generator_obj)
print(res)
res=next(generator_obj)
print(res)
a
b
---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
<ipython-input-20-96eded078e0d> in <module>
      9 res=next(generator_obj)
     10 print(res)
---> 11 res=next(generator_obj)
     12 print(res)

StopIteration:

To learn more about such keywords, click List of all Keywords in Python

Leave a Reply

Your email address will not be published. Required fields are marked *