just-in-time list

Posted by intuited on Stack Overflow See other posts from Stack Overflow or by intuited
Published on 2010-05-25T12:21:26Z Indexed on 2010/05/25 12:31 UTC
Read the original article Hit count: 258

Filed under:
|
|

I'd like to know if there is a class available, either in the standard library or in pypi, that fits this description.

The constructor would take an iterator.

It would implement the container protocol (ie _getitem_, _len_, etc), so that slices, length, etc., would work. In doing so, it would iterate and retain just enough values from its constructor argument to provide whatever information was requested.

So if jitlist[6] was requested, it would call self.source.next() 7 times, save those elements in its list, and return the last one.

This would allow downstream code to use it as a list, but avoid unnecessarily instantiating a list for cases where list functionality was not needed, and avoid allocating memory for the entire list if only a few members ended up being requested.

It seems like a pretty easy one to write, but it also seems useful enough that it's likely that someone would have already made it available in a module.

© Stack Overflow or respective owner

Related posts about python

Related posts about list