The benefits of Python's iteration model
Iteration over all container types is done in a uniform way
- No need to remember different method names and paradigms
- Minimal changes to code when changing data structures
C++ collection of data: queue
queue<int> container;
// assume stuff has been put in the container
queue<int> temp = queue<int>();
while (container.size() > 0) {
int element = container.front();
// do something with element
container.pop();
temp.push(element);
}
delete container;
container = temp;
C++ collection of data: vector
vector<int> container;
// assume stuff has been put in the container
int i, size;
size = container.size()
for (i = 0; i < size; i++) {
int element = container[i];
// do something with element
}
Python collection of data: any collection!
# container is some container with stuff in it
for element in container:
# do something with element
All containers can support iteration
- All built-in containers (list, set, dict, tuple, etc.) support the
container protocol, which includes iteration
- User classes can support iteration as well
The code becomes much more succinct
See examples above. Note that the important part of our code is "do
something with element". In the C++ code, that is buried among the code
that initializes and performs iteration. In Python, there is no
extraneous iteration code.
How Python interprets a for loop