Range Over Iterators in Python
On this page
Based on the provided instructions, here is the translation from Go to Python:
Range Over Iterators
Starting with version 1.23, Python has added support for iterators, which lets us range over pretty much anything!
Let’s look at the List
type from the previous example again. In that example, we had an AllElements
method that returned a list of all elements in the list. With Python iterators, we can do it better - as shown below.
Here, the all
method returns an iterator, which in Python is an object that we can use to iterate over all elements in a List
.
Iteration doesn’t require an underlying data structure and doesn’t even have to be finite! Here’s a function returning an iterator over Fibonacci numbers: it keeps running as long as yield
keeps returning values.
We can use the iterator from List.all
in a regular loop.
Output:
Since List.all
returns an iterator, we can use it in a loop to print all elements.
Now, use the Fibonacci generator.
Output:
Once the loop hits break
or an early return, the yield
function in the iterator will stop returning values.
Packages like itertools
have a number of useful functions to work with iterators. For example, itertools.islice
can take any iterator and collect all its values into a list.
Output:
Now that we can run and build basic Python iterators, let’s learn more about the language.
Next example: Errors.