@kshitij10496
Open Source Developer
Repeated execution of a set of statements
Text
for item in items:
# perform repeated operations
# on each "item"
while some_condition:
# perform operations on some data
for
while
Iterable
Iterator
__iter__ method
__iter__ method must return an "iterator" object
Python3 : __next__() method
Python2: next() method
StopIteration Exception
Trick: Define a class with both __iter__() and __next__()
The "iterator" protocol
list, tuple, dict, string, files
Basically, anything that can be used with a for loop
for item in my_iterable:
# perform operations on item
print(item)
for item in iter(my_iterable):
# perform operations on item
print(item)
In []: squares = [1, 4, 9, 16, 25]
In []: squares_iter = iter(squares)
In []: first_square = next(squares_iter)
....
In []: last_square = next(squares_iter) # 25
In []: new_square = next(squares_iter) # What happens now ?
Call __iter__() method on iterable object
Use next() on the iterator to generate the next item
class yrange(object):
def __init__(self, n):
self.i = 0
self.n = n
def __iter__(self):
return self
def __next__(self):
if self.i < self.n:
i = self.i
self.i += 1
return i
else:
raise StopIteration
class TodoList(object):
def __init__(self, todos=None):
self.todos = todos
def __iter__(self):
return iter(self.todos)
No __next__ method?
iter_items = iter(items)
while True:
try:
item = next(iter_items)
except StopIteration:
break
else:
return item
Under the Hood
natural_numbers = [i for i in itertools.count()]
Try this at your own risk!
Let's be Laaazzzzyyyyyy!
Powerful way to implement iterators
def natural_numbers(start=1):
n = start
while True:
yield n
n += 1
all_natural_numbers = natural_numbers()
But you have no return statement :(
yield ! yield ! yield!
Coroutines vs Subroutines
natural_numbers = (i for i in itertools.count())
Just Kiddin' !
Happy Coding!