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


Groups > comp.lang.python > #82849 > unrolled thread

Re: learning to use iterators

Started byIan Kelly <ian.g.kelly@gmail.com>
First post2014-12-23 12:23 -0700
Last post2014-12-23 12:23 -0700
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: learning to use iterators Ian Kelly <ian.g.kelly@gmail.com> - 2014-12-23 12:23 -0700

#82849 — Re: learning to use iterators

FromIan Kelly <ian.g.kelly@gmail.com>
Date2014-12-23 12:23 -0700
SubjectRe: learning to use iterators
Message-ID<mailman.17160.1419362675.18130.python-list@python.org>

[Multipart message — attachments visible in raw view] — view raw

On Tue, Dec 23, 2014 at 11:55 AM, Seb <spluque@gmail.com> wrote:
>
> Hi,
>
> I'm fairly new to Python, and while trying to implement a custom sliding
> window operation for a pandas Series, I came across a great piece of
> code¹:
>
> >>> def n_grams(a, n):
> ...     z = (islice(a, i, None) for i in range(n))
> ...     return zip(*z)
> ...
>
> I'm impressed at how succinctly this islice helps to build a list of
> tuples with indices for all the required windows.  However, I'm not
> quite following what goes on in the first line of the function.
> Particulary, what do the parentheses do there?

The parentheses enclose a generator expression, which is similar to a list
comprehension [1] but produce a generator, which is a type of iterator,
rather than a list.

In much the same way that a list comprehension can be expanded out to a for
loop building a list, another way to specify a generator is by defining a
function using the yield keyword. For example, this generator function is
equivalent to the generator expression above:

def n_gram_generator(a, n):
    for i in range(n):
        yield islice(a, i, None)

[1]
https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web