Write your own generator expressions
You are familiar with what generators and generator expressions are, as well as its difference from list comprehensions. In this exercise, you will practice building generator expressions on your own.
Recall that generator expressions basically have the same syntax as list comprehensions, except that it uses parentheses () instead of brackets []; this should make things feel familiar! Furthermore, if you have ever iterated over a dictionary with .items(), or used the range() function, for example, you have already encountered and used generators before, without knowing it! When you use these functions, Python creates generators for you behind the scenes.
Now, you will start simple by creating a generator object that produces numeric values.
Deze oefening maakt deel uit van de cursus
Python Toolbox
Oefeninstructies
- Create a generator object that will produce values from
0to30. Assign the result toresultand usenumas the iterator variable in the generator expression. - Print the first
5values by usingnext()appropriately inprint(). - Print the rest of the values by using a
forloop to iterate over the generator object.
Praktische interactieve oefening
Probeer deze oefening eens door deze voorbeeldcode in te vullen.
# Create generator object: result
result = ____
# Print the first 5 values
print(____)
print(____)
print(____)
print(____)
print(____)
# Print the rest of the values
for value in ____:
print(value)