In this tutorial you will learn:
We use iterator when we want to go through all elements of collection. It doesn’t need a specific collection or data type, it works irrespective of implementation.
Iterators in Python
Iterator is an object in Python it implements the iterator protocol. A protocol is something that defines some methods and any class implementing that protocol must implement those methods. In Python the iterator protocol requires two fuctions to be implemented one is the __iter__ function and the other function is the next() function. Iterator object will be returned by the iter function and the next element must be returned by the next function.
- st = "Python"
- val = iter(st)
- print('First letter is: ',next(val))
- print('Second letter is:',next(val))
- print('Third letter is: ',next(val))
- print('Fourth letter is:',next(val))
- print('Fifth letter is: ',next(val))
- print('Sixth letter is: ',next(val), '\n')
Here we can see that the after passing the value to iter we can simply print the values using the next function. Let's look at another example.
- list = ["Python","Testing", 5]
- val = iter(list)
- print(val.__next__(), '\n')
In this example we are using next function with the iterator name which is similar to calling next function and then passing the iterator.
Developing your own Iterator
In order to develop your own iterator you need to implement the iterator protocol and it requires __iter__ and __next__ methods. Iter function is used to initialize the values and returns iterator object. Next function returns the very next value that comes in a list or sequence.
In this example we will create an iterator which will return the number with the power of two on every next iteration.
- class Power:
- def __iter__(self):
- self.num = 0
- return self
- def __next__(self):
- result = 2 ** self.num
- return result
- power = Power()
- it = iter(power)
- print('2 raised to the power 0 :',next(it))
- print('2 raised to the power 1 :',next(it))
- print('2 raised to the power 2 :',next(it))
- print('2 raised to the power 3 :',next(it))
Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.
Virus note: All files are scanned once-a-day by SourceCodester.com for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.
FOR YOUR OWN SAFETY, PLEASE:
1. Re-scan downloaded files using your personal virus checker before using it.
2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.