What are Iterators and Generators in python?

Iterators :
  • An iterator is an object which allows us to traverse through all the elements of a collection, regardless of its specific implementation.
  • An iterator is an object which implements the iterator protocol.
  • The iterator protocol consists of two methods :
    • The __iter__() method, which must return the iterator object
    • The next() method, which returns the next element from a sequence
  • Python has several built-in objects, which implement the iterator protocol. For example lists, tuples, strings, dictionaries or files.
  • Advantages :
    • Cleaner code
    • Iterators can work with infinite sequences
    • Iterators save resources
  • By saving system resources means that when working with iterators, we can get the next element in a sequence without keeping the entire dataset in memory.


Generators :
  • Generators functions allow us to declare a function that behaves like an iterator.
  • A generator yields one value at a time, this requires less memory.
  • Generator uses the yield keyword.
  • For ex :
def fib_gen(n): a, b = 0, 1 for i in range(n): yield a a, b = b, a + b print list(fib_gen(10))

  • Advantage :
    • Memory efficient : Generators are good for calculating large sets of results where you don't know if you are going to need all results, or where you don't want to allocate the memory for all results at the same time.

Comments

Popular posts from this blog

What is composite key?

What are the different data types in Python?

What is __repr__ function?