Changing the output in generator expressions
Great! At this point, you already know how to write a basic generator expression. In this exercise, you will push this idea a little further by adding to the output expression of a generator expression. Because generator expressions and list comprehensions are so alike in syntax, this should be a familiar task for you!
You are given a list of strings lannister
and, using a generator expression, create a generator object that you will iterate over to print its values.
This exercise is part of the course
Python Toolbox
Exercise instructions
- Write a generator expression that will generate the lengths of each string in
lannister
. Useperson
as the iterator variable. Assign the result tolengths
. - Supply the correct iterable in the
for
loop for printing the values in the generator object.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Create a list of strings: lannister
lannister = ['cersei', 'jaime', 'tywin', 'tyrion', 'joffrey']
# Create a generator object: lengths
lengths = ____
# Iterate over and print the values in lengths
for value in ____:
print(value)