Created for
iterator
in Python and the __next__
methoditerator
is any object, implementing the __next__
method__next__
method is called, the iterator should return its "next value".next
, wrapping around __next__
that you can use for convenience.next(it)
is equivalent to it.__next__()
next()
__next__()
iterable
in Python and the __iter__
method__iter__
method__iter__
method returns an iterator.iter()
can also be used to get an iterator from iterable.sets
.iterable
vs iterator
for loop over iterable:
# strings are iterable in Python:
s = "abc"
# iterate over the string iterable with for loop
for i in s:
print(i, end=" ")
# OUTPUT
# a
# b
# c
for loop behaviour using iter() and next():
# strings are iterable in Python:
s = "abc"
# lets get an iterator from the string iterable:
s_iterator = iter(s)
#ask the string iterator for values
print( next(s_iterator) )
print( next(s_iterator) )
print( next(s_iterator) )
# OUTPUT
# a
# b
# c
class SimplestNumbersIterator():
"""Simplest Number Iterator, which can iterate on only two values - 1 and 2."""
def __init__(self):
self.num = 0
self.max = 2
def __iter__(self):
# make the iterator iterable, as well
return self
def __next__(self):
# generate a number to return
if self.num < self.max:
self.num += 1
return self.num
else:
raise StopIteration
class Fibs:
def __init__(self, limit):
self.a = 0
self.b = 1
self.limit = limit
def __next__(self):
self.a, self.b = self.b, self.a + self.b
if ( self.a < self.limit):
return self.a
else:
raise StopIteration
def __iter__(self):
return self
fib_numbers = FibsIterable(30)
for i in fib_numbers:
print( i )
yield
yield
statement can be called a generator!__next__
method of that generator is called, the execution of the function proceeds to the first yield expression,
and the execution is "freezed" - the current state of the function is preserved, and the yield value and the he control is transferred to the caller.
__next__
method of that generator, the exection of the function continues from where it was freezed, and continues as described above.__next__
, the execution code of the function contrains no yield statement - then the StopIteration error is raised.yield
instead of return
def foo_generator():
yield 1
yield 2
foo_gen = foo_generator()
print( next(foo_gen) )
print( next(foo_gen) )
# OUTPUT
# 1
# 2
The Iterator way:
class SimplestNumbersIterator():
"""Simplest Number Iterator, which can iterate on only two values - 1 and 2.
Disclaimer: Use it just to trace how __next__ and __iter__ operators works.This example is not useful in real world!
"""
def __init__(self):
self.num = 0
self.max = 2
def __iter__(self):
return self
def __next__(self):
# generate a number to return
if self.num < self.max:
self.num += 1
print("Iterate on", self.num)
return self.num
else:
raise StopIteration
Play with the full example @repl.it: Custom-Generator-vs-Custom-Iterator
The Generator way:
def simplest_numbers_generator():
"""Simplest Number Generator, yielding only two values - 1 and 2.
Disclaimer: Use it just to trace how next and yield operators works.
This example is not useful in real world!
"""
num = 1
print("Yielding", num)
yield num
num +=1
print("Yielding", num)
yield 2
num +=1
print("Yielding", num)
print("Sory, there is nothing to yield...")
Play with the full example @repl.it: Custom-Generator-vs-Custom-Iterator
#define the generator function:
def numbers_generator(start,end):
num = start
while num<=end:
# yield is almost like return, but it freezes the execution
yield num
num += 1
my_numbers = numbers_generator(1,10)
# iterate over our generator:
for i in my_numbers:
print(i)
nested = [[1, 2], [3, 4], [5]]
def flatten(nested):
for sublist in nested:
for element in sublist:
yield element
print( list(flatten(nested)) )
Naive generation of random "name" like Cyrillic strings
naive_random_names_iterator @repl.it
class EvensRange:
pass
evens_range = EvensRange(1,10)
for i in evens_range(1,10):
print(i)
### expected result
#2
#4
#6
#8
#10
def even_numbers_generator(start,end):
# write your code here
for i in even_numbers_generator(1,10):
print(i)
### expected result
#2
#4
#6
#8
#10
print( chr(1040) )
# 'А''
print( chr(1041) )
# 'Б'
print( chr(1070) )
# 'Ю'
print( chr(1071) )
# 'Я'
These slides are based on
customised version of
framework