- Implementing the iterator, it is a toughest mechanism.
- Implement the iterator mechanism in easy way or simplified manner we are going to use the concept called Generator.
Generators:
- Generator is a function, which contains one or more yield statements.
- yield statement is also like as a return statement in normal function,that yield statement return's value.
- when ever return statement of a function is executed ,function terminates.
- when ever yield statement of a function is executed,function execution will be paused later we can continue the executes the remaining part of the function.
- when ever we call the generator function it internally returns the generator object.
- generator object is also same like as a iterator object.
- when ever we call the Generator function internally _ _iter_ _( ) method and _ _next_ _( ) method are implemented automatically.
- when ever we call the next( ) function on the generator object ,generator function logic will be executed until yield statements.
- if no more elements in generator object,it raises StopIterationException when ever we call next( ).
def my_gen( ):
n=1
print("this is printed first")
yield n
n += 1
print("this is printed second")
yield n
n += 1
print("this is printed last")
yield n
a=my_gen( )
print(a)
print(next(a))
print(next(a))
print(next(a))
print(next(a))
<generator object my_gen at 0x000000A7EBD0C7D8>
this is printed first
1
this is printed second
2
this is printed last
3
Traceback (most recent call last):
File "E:/python_practice/examples/generator.py", line 18, in <module>
print(next(a))
StopIteration
Note:
- Handling the StopIterationException by using For loop .
def my_gen( ):
n=1
print("this is printd first")
yield n
n += 1
print("this is printed second")
yield n
n += 1
print("this is printed last")
yield n
a=my_gen( )
for p in a:
print(p)
this is printd first
1
this is printed second
2
this is printed last
3
Example: reversing the string
def rev_str(my_str):
length=len(my_str)
for i in range(length-1,-1,-1):
yield my_str[i]
x=rev_str("siva")
for p in x:
print(p)
a
v
i
s
No comments:
Post a Comment