Iterators Generators Intro 2 CS week 10 1

  • Slides: 17
Download presentation
Iterators & Generators Intro 2 CS – week 10 1

Iterators & Generators Intro 2 CS – week 10 1

Iterators • Objects that repeatedly return new values • Built-in function next() calls __next__()

Iterators • Objects that repeatedly return new values • Built-in function next() calls __next__() on the iterator 2

Example 3

Example 3

Iterators and Iterables • Another builtin function: iter() creates an iterator 4

Iterators and Iterables • Another builtin function: iter() creates an iterator 4

 • Lists are “iterable”: we can create iterators for them • For loops

• Lists are “iterable”: we can create iterators for them • For loops work on anything that is iterable 5

Iterables and iterators class my_class_iter: class my_class: def __iter__(self): …. def __next__(self): …. def

Iterables and iterators class my_class_iter: class my_class: def __iter__(self): …. def __next__(self): …. def __iter__(self): return self Returns an iterator that goes over this object. Makes the class “iterable”. Iterators are also “iterable” Returns the next item 6

 • What for loops really do: – Get an iterable object – Create

• What for loops really do: – Get an iterable object – Create an iterator for it – Repeatedly call next() on it (until Stop. Iteration is raised) 7

Primes Iterator 8

Primes Iterator 8

9

9

10

10

This is the way to notify that we are out of values. 11

This is the way to notify that we are out of values. 11

Generators • The easiest way to create iterators Similar to “return”, but next time

Generators • The easiest way to create iterators Similar to “return”, but next time will continue from where we stopped 12

A generator for primes 13

A generator for primes 13

 • Let’s also add an iterator to the Stack class, so that we

• Let’s also add an iterator to the Stack class, so that we can run over it with loops. (The iterator here doesn’t remove items) We create the iterator using a generator: 14

A Tree Iterator 15

A Tree Iterator 15

 • Will print: a b c 16

• Will print: a b c 16

Power. Set {1, 2, 3, 4} {1, 2, 4} {1, 2, 3} {1, 2}

Power. Set {1, 2, 3, 4} {1, 2, 4} {1, 2, 3} {1, 2} {1} set() 17