learning to use iterators

Peter Otten __peter__ at web.de
Thu Dec 25 05:34:38 EST 2014


Ian Kelly wrote:

> On Wed, Dec 24, 2014 at 1:34 PM, Rustom Mody <rustompmody at gmail.com>
> wrote:
>> +1 for the slice in succinct form
> 
> Not only more succinct but also more correct. The purpose of islice is to
> slice arbitrary iterables as opposed to just sequences. But this function
> requires a reentrant iterable anyway and returns garbage if you pass it an
> iterator, so there's really no reason for it here. The version using slice
> notation on the other hand will raise a TypeError if you pass it an
> iterator or anything else that can't be sliced, which is preferable to
> silently returning incorrect results.

The natural remedy to that problem is of course itertools.tee():

>>> from itertools import islice, tee
>>> def n_grams(items, n):
...     z = (islice(it, start, None) for start, it in enumerate(tee(items, n)))
...     return zip(*z)
... 
>>> for item in n_grams(iter("abcde"), 3):
...     print("".join(item))
... 
abc
bcd
cde
>>> 





More information about the Python-list mailing list