Range Over Iterators in D Programming Language

Based on the provided input, the target language is Python. Below is the translated Go code example to Python with explanations in Markdown format suitable for Hugo.

Starting with version 3.6, Python added support for iterators, which lets us iterate over pretty much anything!

Let’s look at the `List` type. In this example, we have an `all_elements` method that returns a list of all elements in the list. With Python iterators, we can do it more idiomatically - as shown below.

```python
class List:
    def __init__(self):
        self.head = None
        self.tail = None

class Element:
    def __init__(self, val):
        self.val = val
        self.next = None

def push(lst, v):
    new_elem = Element(v)
    if lst.tail is None:
        lst.head = lst.tail = new_elem
    else:
        lst.tail.next = new_elem
        lst.tail = new_elem

The all_elements method returns an iterator, typically a generator in Python.

def all_elements(lst):
    current = lst.head
    while current is not None:
        yield current.val
        current = current.next

The generator function takes another function as a parameter, called yield by convention. It will yield every element we want to iterate over, and can be used to potentially handle early termination in other scenarios.

Iteration doesn’t require an underlying data structure and doesn’t even have to be finite! Here’s a function returning a generator over Fibonacci numbers: it keeps running as long as elements are needed.

def gen_fib():
    a, b = 1, 1
    while True:
        yield a
        a, b = b, a + b

Here’s how we use the list and generator functions in Python:

def main():
    lst = List()
    push(lst, 10)
    push(lst, 13)
    push(lst, 23)

    for e in all_elements(lst):
        print(e)
    
    all_vals = list(all_elements(lst))
    print("all:", all_vals)
    
    for n in gen_fib():
        if n >= 10:
            break
        print(n)

if __name__ == "__main__":
    main()

Output after running the program:

10
13
23
all: [10, 13, 23]
1
1
2
3
5
8

Now that we can implement and use iterators, let’s learn more about the language.

Next example: Errors.