Michael J. Fromberger
Michael.J.Fromberger at Clothing.Dartmouth.EDU
Fri Sep 21 14:54:20 CEST 2007
In article <fctrc1$doh$1 at news.nems.noaa.gov>,
George Trojan <george.trojan at noaa.gov> wrote:
> A while ago I found somewhere the following implementation of frange():
> def frange(limit1, limit2 = None, increment = 1.):
> Range function that accepts floats (and integers).
> frange(-2, 2, 0.1)
> frange(10, increment = 0.5)
> The returned value is an iterator. Use list(frange) for a list.
> if limit2 is None:
> limit2, limit1 = limit1, 0.
> limit1 = float(limit1)
> count = int(math.ceil(limit2 - limit1)/increment)
> return (limit1 + n*increment for n in range(count))
> I am puzzled by the parentheses in the last line. Somehow they make
> frange to be a generator:
> >> print type(frange(1.0, increment=0.5))
> <type 'generator'>
> But I always thought that generators need a keyword "yield". What is
> going on here?
The expression returned is a "generator expression",
return (limit1 + n*increment for n in range(count))
Thus, although frange itself is not written as a generator, it does
return a generator as its result. The syntax is like that of list
Michael J. Fromberger | Lecturer, Dept. of Computer Science
http://www.dartmouth.edu/~sting/ | Dartmouth College, Hanover, NH, USA
More information about the Python-list