learning to use iterators

Ian Kelly ian.g.kelly at gmail.com
Tue Dec 23 14:23:45 EST 2014


On Tue, Dec 23, 2014 at 11:55 AM, Seb <spluque at 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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20141223/ef079fa7/attachment.html>


More information about the Python-list mailing list