Difference Between Generator and Iterator in Python

1. Introduction

In Python, iterators and generators are concepts used for iterating over data. An iterator is an object that enables a programmer to traverse through all the elements in a collection, regardless of its specific implementation. A generator, on the other hand, is a more concise way to create iterators. It's a function that uses yield to provide a sequence of values to the one iterating over it.

2. Key Points

1. Creation: Iterators are created using iter() or defining a class with __iter__() and __next__(), generators with a function and yield.

2. Memory Usage: Iterators may use more memory for larger collections, and generators use less memory.

3. State: Generators maintain state in local variables, and iterators can maintain state in class-level variables.

4. Reusability: Iterators can be reused, but generators cannot be reused once exhausted.

3. Differences

Aspect Iterator Generator
Creation Using iter() or __iter__() and __next__() Using a function with yield
Memory Usage Higher for large collections Lower
State In class-level variables In local variables
Reusability Can be reused Cannot be reused once exhausted

4. Example

# Example of an Iterator
class CountIterator:
    def __init__(self, max):
        self.max = max
        self.num = 0

    def __iter__(self):
        return self

    def __next__(self):
        if self.num < self.max:
            self.num += 1
            return self.num
        else:
            raise StopIteration

# Example of a Generator
def count_generator(max):
    num = 1
    while num <= max:
        yield num
        num += 1

# Creating instances
iterator = CountIterator(3)
generator = count_generator(3)

# Iterating
iterator_output = [i for i in iterator]
generator_output = [g for g in generator]

Output:

Iterator Output:
[1, 2, 3]
Generator Output:
[1, 2, 3]

Explanation:

1. The iterator is a class that implements the iterator protocol and can be reused.

2. The generator is a simpler way to create an iterator using a function. Once exhausted, it cannot be restarted or reused.

5. When to use?

- Use iterators when you need a reusable object that can traverse through a collection of data.

- Use generators for a simple and concise way to create iterators, especially useful when dealing with large datasets or streams of data.

Related Python Posts:

Difference Between Local and Global Variables in Python

Difference Between List and Tuple in Python

Difference Between Array and List in Python

Difference Between List and Dictionary in Python

Difference Between List, Tuple, Set and Dictionary in Python

Difference Between a Set and Dictionary in Python

Difference between for loop and while loop in Python

Difference Between pass and continue in Python

Difference Between List append and extend in Python

Difference Between == and is operator in Python

Difference Between Deep and Shallow Copy in Python

Class Method vs Static Method in Python

Class Method vs Instance Method in Python

Difference Between List and Set in Python

Difference Between Generator and Iterator in Python

Difference Between str and repr in Python

Method Overloading vs Overriding in Python

Difference Between Dictionary and Tuple in Python

Difference Between Dictionary and Object in Python

Difference Between Mutable and Immutable in Python

Difference Between Interface and Abstract Class in Python

Difference Between Python Script and Module

Difference Between for Loop and Iterator in Python

Comments