[Python-Dev] [Python-ideas] minmax() function returning (minimum, maximum) tuple of a sequence

Xavier Morel python-dev at masklinn.net
Mon Oct 11 08:06:13 CEST 2010


On 2010-10-11, at 07:56 , Carl M. Johnson wrote:
> On Sun, Oct 10, 2010 at 2:55 PM, Zac Burns <zac256 at gmail.com> wrote:
>> This could be generalized and placed into itertools if we create a function
>> (say, apply for lack of a better name at the moment) that takes in an
>> iterable and creates new iterables that yield each from the original
>> (avoiding the need for a list) holding only one in memory. Then you could
>> pass the whatever function you wanted to run the iterables over an get the
>> result back in a tuple.
> 
> Time machine partially beat you to this one. Look at the docs on itertools.tee
> 
>    tee(it, n=2) --> (it1, it2 , ... itn) splits one iterator into n
> 
> Can be used like so:
> 
>>>> it = iter(range(100))
>>>> it1, it2 = itertools.tee(it)
>>>> max(it1)
> 99
>>>> min(it2)
> 0
> 
> This doesn't quite have the memory characteristics you describe

That's an understatement. As the documentation indicates, if you're going to fully consume the iterator the first time around instead of iterating both in near-lockstep (combining islice and map for instance) you're better off serializing to a list and then using that list twice, memory-wise.

> but it's about as good as you can expect in a single threaded environment.
You could also have coroutines, but they cooperate explicitly so you'd have to "fix" min and max (and any other function you can get your hands on, really) in order to allow them to act as coroutines, I think.


More information about the Python-Dev mailing list