Title: Functions Vs. Generators
Slug: functions_vs_generators
Summary: Functions Vs. Generators in Python.
Date: 2016-01-23 12:00
Category: Python
Tags: Basics
Authors: Chris Albon
Interesting in learning more? Check out Fluent Python
In [1]:
# Create a function that
def function(names):
# For each name in a list of names
for name in names:
# Returns the name
return name
In [2]:
# Create a variable of that function
students = function(['Abe', 'Bob', 'Christina', 'Derek', 'Eleanor'])
In [3]:
# Run the function
students
Out[3]:
Now we have a problem, we were only returned the name of the first student. Why? Because the function only ran the for name in names iteration once!
In [4]:
# Create a generator that
def generator(names):
# For each name in a list of names
for name in names:
# Yields a generator object
yield name
In [5]:
# Same as above, create a variable for the generator
students = generator(['Abe', 'Bob', 'Christina', 'Derek', 'Eleanor'])
Everything has been the same so far, but now things get interesting. Above when we ran students when it was a function, it returned one name. However, now that students refers to a generator, it yields a generator object of names!
In [6]:
# Run the generator
students
Out[6]:
What can we do this a generator object? A lot! As a generator students will can each student in the list of students:
In [7]:
# Return the next student
next(students)
Out[7]:
In [8]:
# Return the next student
next(students)
Out[8]:
In [9]:
# Return the next student
next(students)
Out[9]:
It is interesting to note that if we use list(students) we can see all the students still remaining in the generator object's iteration:
In [10]:
# List all remaining students in the generator
list(students)
Out[10]: