iterator clone

Marc 'BlackJack' Rintsch bj_666 at gmx.net
Mon Jul 14 01:06:12 EDT 2008


On Sun, 13 Jul 2008 18:51:19 -0700, Yosifov Pavel wrote:

>> Well, I think Python's iterators, especially the generators, are beautiful.
>> More importantly, I think there is no general way to make iterators
>> copyable, regardless of the programming language. The problem is that most
>> of the useful ones depend on external state.
> 
> Hmm, but tee() de facto do it (clone iterator) and ignore side-effects
> of iterator ("external" state). And tee() create independent
> **internal** state of iterator (current position).

`tee()` doesn't copy the iterator or its internal state but just caches
it's results, so you can iterate over them again.  That makes only sense
if you expect to use the two iterators in a way they don't get much out of
sync.  If your usage pattern is "consume iterator 1 fully, and then
re-iterate with iterator 2" `tee()` has no advantage over building a list
of all results of the original iterator and iterate over that twice. 
`tee()` would be building this list anyway.

> But **external** state - is headache of programmer. So,
> iterator/generator have to be method for copy itself (the tee()
> implementation) or be "re- startable". Why not?

Because it's often not possible without generating a list with all
results, and the advantage of a low memory footprint is lost.

Ciao,
	Marc 'BlackJack' Rintsch



More information about the Python-list mailing list