Iterators, iterables and special objects

Peter Slížik peter.slizik at gmail.com
Tue Jul 21 05:32:59 EDT 2020


Hi list, two related questions:

1. Why do functions used to iterate over collections or dict members return
specialized objects like

type(dict.keys()) -> class 'dict_keys'
type(dict.values()) -> class 'dict_values'
type(dict.items()) -> class 'dict_items'
type(filter(..., ...)) -> class 'filter'
type(map(..., ...)) -> class 'map'
type(enumerate(...)) -> class 'enumerate'

instead of returning some more general 'iterable' and 'view' objects? Are
those returned objects really that different from one another that it makes
sense to have individual implementations?

2. Why do these functions return iterators instead of iterables? First, I
find it confusing - to me, it is the loop's job to create an iterator from
the supplied iterable, and not the object that is being iterated over. And
second, with this design, iterators are required to be iterables too, which
is confusing as hell (at least for people coming from other languages in
which the distinction is strict).

Thanks,
Peter


More information about the Python-list mailing list