Range Over Iterators in R Programming Language
On this page
Our first program demonstrates how to iterate over a custom list and generate Fibonacci sequences using iterators. Here’s the full source code translated to Python:
To run this Python code, simply execute it as a script.
Explanation:
Element Class: This defines the structure of an element in the list, containing a value and a pointer/reference to the next element.
List Class: This class manages the linked list and provides methods to add (
push
) and iterate over all elements (all
).gen_fib Function: This function generates an infinite sequence of Fibonacci numbers, which can be iterated until a specific condition is met (e.g., values less than 10).
main Function:
- Creates a list and pushes some elements into it.
- Iterates over the list elements and prints each one.
- Collects all elements of the list into a Python list and prints them.
- Generates Fibonacci numbers and prints them until a value reaches 10.
This translated Python version makes use of Python’s generator functions (yield
) to replicate the iterator behavior.