Created for
__iter__
method.iter
method should do, is defined in "The Iterator Protocol" - a concept, present in most modern programming languages.__iter__
method__iter__
method is called itarable__iter__
method returns an iterator.__next__
, which is callable without any arguments.next
rather than __next__
__next__
method__next__
method is called iterator__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__()
iter()
can be used to get an iterator from an iterable object.
iterable = [1,2,3]
iterator = iter(iterable)
print( next(iterator) )
print( next(iterator) )
print( next(iterator) )
#1
#2
#3
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!yield
instead of return
def simple_generator():
yield 1
#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)) )
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