learning to use iterators

Terry Reedy tjreedy at udel.edu
Tue Dec 23 15:46:27 EST 2014


On 12/23/2014 1:55 PM, Seb wrote:

>>>> 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 parenthesized expression is a generator expression.  The ()s are 
part of the syntax and may only be omitted when the expression is the 
argument of a function call, as in

 >>> list((i for i in range(0, 7, 2)))
[0, 2, 4, 6]
 >>> list(i for i in range(0, 7, 2))
[0, 2, 4, 6]

-- 
Terry Jan Reedy




More information about the Python-list mailing list