Day 41: Write Generator Function


What is generator function?

– It produces generator object when it called.
– It defines like general function using def keyword.
– Its return value is using yield keyword. It yields a sequence of values instead of a single value.

How to build a generator?

A generator function is defined as you do a regular function, but whenever it generates a value, it uses the keyword yield instead of return. Let us look at the exercise in DataCamp’s tutorial which walk me through how to write generator function in Python.

The instructions as below:
1. Complete the function header for the function get_lengths() that has a single parameter, input_list.
2. In the for loop in the function definition, yield the length of the strings in input_list.
3. Complete the iterable part of the for loop for printing the values generated by the get_lengths() generator function. Supply the call to get_lengths(), passing in the list lannister.

The code as below:

# Create a list of strings
lannister = ['cersei', 'jaime', 'tywin', 'tyrion', 'joffrey']

# Define generator function get_lengths
def get_lengths(input_list):
    """Generator function that yields the
    length of the strings in input_list."""

    # Yield the length of a string
    for person in input_list:
        yield len(person)

# Print the values generated by get_lengths()
for value in get_lengths(lannister):
    print(value)

#Output:
#6
#5
#5
#6
#7

Summary of the day:

  • Generator function.
  • Keyword: yield.
Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s