Search a sequence for its minimum and stop as soon as the lowest possible value is found

Jussi Piitulainen jussi.piitulainen at
Sun Jan 8 01:06:52 EST 2017

Paul Rubin writes:

> Jussi Piitulainen writes:
>>> Use itertools.takewhile
>> How? It consumes the crucial stop element:
> Oh yucch, you're right, it takes it from both sides.  How about this:
>     from itertools import takewhile, islice
>     def minabs(xs):
> 	a = iter(xs)
> 	m = min(map(abs,takewhile(lambda x: x!=0, a)))
> 	z = list(islice(a,1))
> 	if z: return 0
> 	return m

That would return 0 even when there is no 0 in xs at all.

(It would also return the absolute value, not a value whose absolute
value is minimal, but that is easy to fix.)

More information about the Python-list mailing list