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


Groups > comp.lang.python > #82854

Re: learning to use iterators

From Terry Reedy <tjreedy@udel.edu>
Subject Re: learning to use iterators
Date 2014-12-23 15:46 -0500
References <878uhyb3hq.fsf@net82.ceos.umanitoba.ca>
Newsgroups comp.lang.python
Message-ID <mailman.17165.1419367616.18130.python-list@python.org> (permalink)

Show all headers | View raw


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

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


Thread

Re: learning to use iterators Terry Reedy <tjreedy@udel.edu> - 2014-12-23 15:46 -0500

csiph-web