PREV
Here we are going to discuss about advance topics in python.They are
1. Python Iterator
2. Python Generator
3. Python @Property
4. Python Decorator
1. Python Iterators:
Iteration is a simple an object,it can be iterated upto given limit.It can allow the user to access or traverse through the all items which are collected without any prior knowldge
Python Iterator has been implemented by using iterator tool,it is consists of two Methods.They are
1. __iter__()
2. __next__()
1. __iter__():
This method returns an iterator object
2. __next__():
- This method returns the next element in the sequence of an object
- Before going to discuss about this methods ,we will little understanding the standard loops.
Take an example as a for loop
here we can consider list which have the elements as an int
|
1 2 3 4 5 |
data=[1,2,3,4,5] for i in data: print (“i is:”,i) |
Output:
|
1 2 3 4 5 6 7 8 9 |
1 2 3 4 5 |
Now we can go thorough internally,what is happening
- When we are going to work with loops internally it will use __iter__() and __next__() methods,here __iter__() will iterate the items one by one and __next__() will print the next items in collected.
Now below we are going to demonstrate the usage of iter and next.
>>> data=[1,2,3,4,5]
>>> d_obj=iter(data)
>>> next(d_obj)
1
>>> next(d_obj)
2
>>> next(d_obj)
3
>>> next(d_obj)
4
>>> next(d_obj)
5
>>> next(d_obj)
Traceback (most recent call last):
File “<stdin>”, line 1, in <module>
StopIteration
>>>
