Iterators and Generators in python - Letsprogram

Share:

Iterators


When we talk about iteration we may remember like i++ where i value iterates under a condition or Objects can be looped over
for statement.

>>>nums = [1,2,3,4]
>>>for num in nums:
       print(num)

1
2
3
4



The for loop just acts as an iterator. But there is another way we can use it is iter method

>>>it = iter(nums)
>>>print(it)
<list_iterator object at 0x000001DBB1A70190>
>>>print(it.__next__())
1
>>>print(it.__next__())
2

When you look at the above code by using the __next__() method for iterator object it is printing the value in the nums list. Again after using this method, it is printing the next value in the list, not the first one it is like it holds the previous value or index of the list. You can iterate by also using the next method.

>>>print(next(it))
3

This style of access is clear, concise, and convenient. The use of iterators pervades and unifies Python. Behind the scenes, the for statement calls iter() on the container object. The function returns an iterator object that defines the method __next__() which accesses elements in the container one at a time. When there are no more elements, __next__() raises a StopIteration exception which tells the for loop to terminate. 

>>>next(it)
4
>>>next(it)
Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    next(it)
StopIteration

See the mechanism of iterators with an example by a  class


Generators


Generators are used to create iterators. These are powerful tools to build an iterator. They are just like normal functions but instead of using a return statement here, the yield is used whenever it returns a value.

Each time next() is called on it. Generator remembers the last value executed and resumes where it left off.

>>> def reverse(data):
        for index in range(len(data)-1,-1,-1):
            yield data[index]

>>> for char in reverse('golf'):
        print(char)

f
l
o
g

Anything that can be done by using generators can also be done by using iterators in class. In the above program in iterators, we had to define the __iter__() and __next__() method but in generators, there is no need to define them. When generators terminate they also raise StopIteration and they save program states these features make it easy to create iterators with no more effort than writing a regular function.

Some simple generators can be coded succinctly as expressions using a syntax similar to list comprehensions but with parentheses instead of square brackets. These expressions are designed for situations where the generator is used right away by an enclosing function. Generator expressions are more compact but less versatile than full generator definitions and tend to be more memory friendly than equivalent list comprehensions.

generator expressions

No comments

F