reading-notes

Pythonisms

Readings

Notes

Iterators

In Python, an iterator is an object that produces a sequence of values, typically used in loops

# Define the class
class EvenIterator:
    def __init__(self):
        self.current = 0
        self.limit = 10
    def __iter__(self):
        return self
    def __next__(self):
        if self.current >= self.limit:
            raise StopIteration
        else:
            self.current += 2
            return self.current

# Use in a for loop like this:
for num in EvenIterator():
    print(num)
# Output: 2,4,6,8,10

Dunder Methods

Generators

A generator is a function that produces a sequence of values, typically used in loops, similar to an iterator. The main difference is that generators use the yield keyword to return values one at a time, rather than returning all values at once as iterators do. So generators look like regular functions but instead of using the return statement, they use yield to pass data back to the caller.

When a generator function is called, it returns a generator object, which can be used to iterate over the sequence of values. Each time the yield keyword is encountered in the function, the current value is returned to the caller, and the function’s state is saved. The next time the generator is called, execution resumes from where it left off, and the function continues until it encounters another yield statement.

Generators are useful for generating large sequences of values, particularly when it would be memory-intensive to store all the values at once. Because generators produce values on the fly, they can be more memory-efficient than other approaches.

# Generates the first 5 even numbers
def even_numbers():
    current = 0
    limit = 10
    while current < limit:
        yield current
        current += 2

# Call the even_numbers generator
for num in even_numbers():
    print(num)
# Output: 0,2,4,6,8

NOTE: The even_numbers() function is defined like a normal function, but it uses the yield keyword to generate values one at a time.