Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #82912

Re: learning to use iterators

From Peter Otten <__peter__@web.de>
Subject Re: learning to use iterators
Date 2014-12-25 11:34 +0100
Organization None
References <878uhyb3hq.fsf@net82.ceos.umanitoba.ca> <mailman.17185.1419433939.18130.python-list@python.org> <8a840698-a3be-4889-9ddd-756a553e6f48@googlegroups.com> <CALwzid=VT78RHJVuznZ+nWKBuYMZsh0z7dt9Ay2pKUbjN0zaXw@mail.gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.17198.1419503693.18130.python-list@python.org> (permalink)

Show all headers | View raw


Ian Kelly wrote:

> On Wed, Dec 24, 2014 at 1:34 PM, Rustom Mody <rustompmody@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
>>> 

Back to comp.lang.python | Previous | NextPrevious in thread | Find similar | Unroll thread


Thread

Re: learning to use iterators Vito De Tullio <vito.detullio@gmail.com> - 2014-12-24 16:12 +0100
  Re: learning to use iterators Rustom Mody <rustompmody@gmail.com> - 2014-12-24 12:34 -0800
    Re: learning to use iterators Ian Kelly <ian.g.kelly@gmail.com> - 2014-12-24 22:36 -0700
    Re: learning to use iterators Peter Otten <__peter__@web.de> - 2014-12-25 11:34 +0100

csiph-web