A generator object in the Python computer programming language is totally different from a normal function, as it returns multiple values one by one through the yield statement.
As you may already know, a normal function in Python returns one value to the caller through the return statement. One can easily access the value returned by the normal function just by calling it.
What about accessing the values of a generator object in the Python computer programming language? What approach should the coder take to get the values returned by the generator function?
Let’s build a generator function first, and later access its values with the help of a Python for loop statement.
Let’s build a generator function
The coder can easily code a generator function by making use of the Python’s def statement which is being used to define normal functions.
Let’s define the skeleton of the generator function first. Make sure to launch a fresh interactive console in your own operating system so you can practice the code being shared in here.
def gen_func(): pass
For now, the above functions does not do anything. It is just a skeleton for our generator.
Let’s define a local list inside the above function; and insert some elements in it.
def gen_function(): l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10,] return l
As you can see from the above piece of Python code, the function gen_function defines a normal function and returns a list object to the caller.
Let’s call the above function in the Python’s interactive console and see the result the comes out.
g = gen_functiom() print(g)
Once I managed to execute the above piece of Python code in my interactive console, I got back the following output.
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
At the moment, the function gen_function is a normal one. It is not a generator yet.
Let’s customize the gen_function so we can build a generator out of it.
def gen_function(): l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10,] for el in l: yield el
After you have managed to customize the code so it looks like the one being shown above, call the function gen_function again with the help of the following command.
If you have customized the gen_function the right way, you should get the following output.
<generator object gen_function at 0x108660a00>
Now let’s try to access the values of our generator object by making use of a for loop.
gen_obj = gen_function() for el in gen_obj:print(el)
After executing the above piece of Python code, you should get the following output.
1 2 3 4 5 6 7 8 9 10
As you can see from the examples being shared through this blog post, we can easily access the results of a generator object with the help of a for loop statement.