This is the lecture note of CS61A - Lecture 15.
Iterators
Iterators are common interface in many programming languages, and they're used in Python as a way to access the elements of lots of different containers. A container can provide an iterator which in turn provides access to its elements in order.
Two built-in functions:
- iter(iterable): Return an iterator over the elements of an iterable value
- next(iterator): Return the next element in an iterator
1 | 1, 2], 3, 4, 5] s = [[ |
Dictionary Iteration
1 | # dictionary iteration demo |
For Statements
For statements iterate over iterable values. They can also iterate over iterators themselves.
1 | range(3, 6) r = |
Built-in Iterator Functions
- lazy computation: means the result is only computed when it has been requested
Map Demo
1 | 'b', 'c', 'd'] bcd = [ |
Filter Demo
1 | def double(x): |
Zip Demo
1 | # example: zip |
1 | # demo: palindrome |
Generators
A gernerator is a special kind of iterator. The special thing is that a generator is returned from a generator function.
A generator function is a function that yields values instead of returning values.
- normal function returns once;
- generator function yield multiple times;
1 | def plus_minus(x): |
Generator functions can return generators. But they often process iterators in the course of their execution.
Let's finish today's lecture with the following examples.
1 | def prefixes(s): |