Final state of underlying sequence in islice

Shashank Singh shashank.sunny.singh at gmail.com
Thu Nov 4 12:42:03 EDT 2010


Hi,

Apologies if this has been discussed in this list before. Google has not
been very helpful in locating any such
previous discussion.

Are there any promises made with regard to final state of the underlying
sequence that islice slices?
for example consider this

>>> from itertools import *
>>> c = count()
>>> list(islice(c, 1, 3, 50))
[1]
>>> c.next()
51

Now, the doc [1] says "If *stop* is None, then iteration continues until the
iterator is exhausted, if at all; otherwise, it stops at the specified
position".
It clearly is not stopping at stop (3).

Further, the doc gives an example of how this is *equivalent* to a generator
defined in the same section. It turns out, these two are not exactly the
same if the side-effect of the code is considered on the underlying
sequence.

Redefining islice using the generator function defined in the doc gives
different (and from one pov, expected) result
>>> def islice(iterable, *args):
...     # islice('ABCDEFG', 2) --> A B
...
>>> c = count()
>>> list(islice(c, 1, 3, 50))
[1]
>>> c.next()
2

While "fixing" this should be rather easy in terms of the change in code
required it might break any code depending
on this seemingly incorrect behavior.

[1]. http://docs.python.org/library/itertools.html#itertools.islice
-- 
Regards
Shashank Singh
shashank.sunny.singh at gmail.com
http://www.cse.iitb.ac.in/~shashanksingh<http://www.cse.iitb.ac.in/%7Eshashanksingh>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20101104/5474cfd1/attachment.html>


More information about the Python-list mailing list