Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- In Python, an iterator is an object that can be iterated (looped) upon. An object which will return data, one element at a time. They are used to represent a stream of data. An iterator object has two methods, __iter__() and __next__(). The __iter__() method returns the iterator object itself. The __next__() method returns the next value from the iterator, and raises StopIteration when there are no more values to return.
- A generator is a special type of iterator that is created using a function. A generator function is defined like a normal function, but instead of returning a value, it yields a value using the yield keyword. When a generator function is called, it does not execute the function body immediately. Instead, it returns a generator object that can be used to execute the function body lazily, one statement at a time.
- An enumerator is an object that generates an iterable series of values. It can be created using the enumerate() function, which takes an iterable object as an argument and returns an iterator of tuples. The first element of each tuple is the index of the value in the iterable, and the second element is the value itself.
- Here is an example that demonstrates the difference between an iterator, a generator, and an enumerator in Python:
- # Iterator example
- # The Fibonacci sequence is a series of numbers in which each number is the sum of the previous two.
- # The first two numbers in the sequence are 0 and 1, and the rest of the numbers are the sum of the
- # previous two.
- class FibonacciIterator:
- def __init__(self, max):
- self.max = max
- self.a = 0
- self.b = 1
- def __iter__(self):
- return self
- def __next__(self):
- result = self.a
- if result > self.max:
- raise StopIteration
- self.a, self.b = self.b, self.a + self.b
- return result
- fib_iterator = FibonacciIterator(10)
- for i in fib_iterator:
- print(i)
- # Output: 0 1 1 2 3 5 8
- # Generator example
- def fibonacci_generator(max):
- a, b = 0, 1
- while a < max:
- yield a
- a, b = b, a + b
- for i in fibonacci_generator(10):
- print(i)
- # Output: 0 1 1 2 3 5 8
- # Enumerator example
- fruits = ['apple', 'banana', 'mango']
- for index, fruit in enumerate(fruits):
- print(f'{index}: {fruit}')
- # Output:
- # 0: apple
- # 1: banana
- # 2: mango
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement