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


Groups > comp.lang.python > #82849

Re: learning to use iterators

References <878uhyb3hq.fsf@net82.ceos.umanitoba.ca>
From Ian Kelly <ian.g.kelly@gmail.com>
Date 2014-12-23 12:23 -0700
Subject Re: learning to use iterators
Newsgroups comp.lang.python
Message-ID <mailman.17160.1419362675.18130.python-list@python.org> (permalink)

Show all headers | View raw


[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

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


Thread

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

csiph-web