Advertisement
marcusziade

iterators, generators and enumerators in python

Jan 2nd, 2023
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.34 KB | Source Code | 0 0
  1. 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.
  2.  
  3. 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.
  4.  
  5. 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.
  6.  
  7. Here is an example that demonstrates the difference between an iterator, a generator, and an enumerator in Python:
  8.  
  9. # Iterator example
  10.  
  11. # The Fibonacci sequence is a series of numbers in which each number is the sum of the previous two.
  12. # The first two numbers in the sequence are 0 and 1, and the rest of the numbers are the sum of the
  13. # previous two.
  14.  
  15. class FibonacciIterator:
  16.     def __init__(self, max):
  17.         self.max = max
  18.         self.a = 0
  19.         self.b = 1
  20.  
  21.     def __iter__(self):
  22.         return self
  23.  
  24.     def __next__(self):
  25.         result = self.a
  26.         if result > self.max:
  27.             raise StopIteration
  28.         self.a, self.b = self.b, self.a + self.b
  29.         return result
  30.  
  31. fib_iterator = FibonacciIterator(10)
  32. for i in fib_iterator:
  33.     print(i)
  34.  
  35. # Output: 0 1 1 2 3 5 8
  36.  
  37. # Generator example
  38.  
  39. def fibonacci_generator(max):
  40.     a, b = 0, 1
  41.     while a < max:
  42.         yield a
  43.         a, b = b, a + b
  44.  
  45. for i in fibonacci_generator(10):
  46.     print(i)
  47.  
  48. # Output: 0 1 1 2 3 5 8
  49.  
  50. # Enumerator example
  51.  
  52. fruits = ['apple', 'banana', 'mango']
  53.  
  54. for index, fruit in enumerate(fruits):
  55.     print(f'{index}: {fruit}')
  56.  
  57. # Output:
  58. # 0: apple
  59. # 1: banana
  60. # 2: mango
  61.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement