On Wed, Dec 16, 2009 at 12:38 PM, Anh Hai Trinh <anh.hai.tr...@gmail.com> wrote: > On Dec 16, 2:48 pm, Brendan Miller <catph...@catphive.net> wrote: > >> No, that's what I'm getting at... Most of the existing mutating >> algorithms in python (sort, reverse) operate over entire collections, >> not partial collections delimited by indexes... which would be really >> awkward anyway. > > Ok it can be done! The code is here: <http://gist.github.com/258134>. > > >>> from listagent import listagent > >>> x = [22, 7, 2, -5, 8, 4] > >>> listagent(x)[1:].sort() > >>> x > [22, -5, 2, 4, 7, 8] > >>> listagent(x)[::2].reverse() > >>> x > [7, -5, 2, 4, 22, 8] > > Basically the agent refers to the original list only by "address > translation", and indeed made no copy of anything whatever! I > implemented Shell sort but I suppose others are possible. > > The implementation is incomplete, for now you cannot do slice > assignment, i.e. > > a = listagent(x)[::-2] > a[1:] = [4, 2] > > but it should be easy to implement, and I'm too sleepy.
Very cool, that's more or less what I was thinking of. I have a couple of thoughts: 1. Since [:] by convention already creates a copy, it might violate people's expectations if that syntax were used. 2. I'd give the listagent the mutable sequence interface, but and then make new algorithms (except sort and reverse which are required by the mutable sequence) as functions that just expect an object that mutable sequence compatible. That way the algorithm is decoupled from the datastructure, and the same code can handle both lists and listagents, or even potentially other datastructures that can expose the same interface. For instance, I was coding up some stl algorithms in python including next_permutation. So, if you wanted to make a generic next_permutation in python, you wouldn't want to make it a member of listagent, because then regular lists couldn't use it conveniently. However, if it were just a function that accepted anything that implemented mutable sequence, it could operate both over lists and over listagent without any conversion. -- http://mail.python.org/mailman/listinfo/python-list