Posts

Showing posts with the label generator

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. Gene