iterators and views of lists

Anh Hai Trinh anh.hai.trinh at gmail.com
Wed Dec 16 21:38:47 CET 2009


On Dec 16, 2:48 pm, Brendan Miller <catph... at 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.

Peace,
----aht



More information about the Python-list mailing list