Iterators In Python¶
Iterators in python:¶
Iterators in python is one of the simple and strong features of python. We already know that in python everything's an object. So, iterator is also a python object, which has a special method called "next". In python iterator acts like a container. When we call method "next" on the iterator object. It will creates and return the objects onfly. After returning the object it will longer available to access again. Python provides the built-in keyword "next". when we call the "next" with iterator object it will call the object method "next" which will return the object onfly.
usage of iterators in python¶
We can convert any object to an iterable object if only if it has a method "iter" implemented. To convert a object to an iterable object we need to call the python's built-in function "iter" with the object as an argument. It will call the "iter" method which is responsible to return iterable objects.
Example:¶
class Fibonacci:
def __init__(self, limit):
self.limit = limit
self.counter = 0
self.fib_data = []
def __iter__(self):
return self
def next(self):
self.counter += 1
if self.counter > self.limit:
raise StopIteration
if len(self.fib_data) < 2:
self.fib_data.append(1)
else:
self.fib_data = [
self.fib_data[-1], self.fib_data[-1] + self.fib_data[-2]
]
return self.fib_data[-1]
# Case1
for i in Fibonacci(3):
print(i)
# Output:
# 1
# 1
# 2
# Case2
iter_obj = Fibonacci(3)
print(next(iter_obj))
print(next(iter_obj))
print(next(iter_obj))
print(next(iter_obj))
# Output:
# 1
# 1
# 2
# Traceback (most recent call last):
# File "fibonacci.py", line 35, in <module>
# print next(iter_obj)
# StopIteration
Lets see usage of iterators with python builtin methods
# convert list to iterable object
l = [1,2,3]
iter_obj = iter(l)
print(iter_obj.next())
# Output: 1
# convert dict to iterable object
d = {1:2, 3:4}
iter_obj = iter(d)
print(iter_obj.next())
# Output: 1
# convert list to iterable object
t = (1,2,3)
iter_obj = iter(t)
print(iter_obj.next())
# Output: 1