On Tue, Dec 23, 2014 at 11:55 AM, Seb <splu...@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
-- https://mail.python.org/mailman/listinfo/python-list