learning to use iterators

Seb spluque at gmail.com
Tue Dec 23 13:55:13 EST 2014


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?

Thanks,


+--- Footnotes ---+
¹ http://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html#sliding-windows-n-grams-using-zip-and-iterators

-- 
Seb




More information about the Python-list mailing list