10.1 Iterators&Generators.pdf

(1043 KB) Pobierz
Iterators and Generators
Iterators allow us to iterate through a sequence of element I.e, visiting each
element once in a sequence
dictionary
We can pass any sequence to the iterator like
list , string , tuple , set and
In python there is a built in function called
iter
for iteration
#next(itr) give next element in sequence
We can write our own iterators which are called
“GENERATORS”
they work just
like iterators
Lets see this with an example which displays days of a week and once the
sequence is completed and called again it should return the first value and so
on…
# For a loop to remain in same
state we use
yield
it’ll not stop
the function but keep function on
hold and return value
Zgłoś jeśli naruszono regulamin