iterators and views of lists

Anh Hai Trinh anh.hai.trinh at gmail.com
Thu Dec 17 11:41:19 EST 2009


> 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.

Indeed, listagent returns self on __getitem__[:]. What I meant was
this:

  x = [0, 1, 2, 3, 4, 5, 6, 7]
  a = listagent(x)[::2]
  a[:] = listagent(x)[::-2]

And we get x = [7, 1, 5, 3, 3, 5, 1, 7], the copying happens in-place,
of course.


> 2. I'd give the listagent the mutable sequence interface

Done!  I put the code in a repository here for those who might be
interested:
<http://github.com/aht/listagent.py>.

In retrospect, the Python gurus here was right though. Copy, modify
then replace is good enough, if not better since items are just
pointers instead of values. For reversing, you need to translate all
the indices (which cost exactly one addition and one multiplication
per index). Is that cheaper than copying all the pointers to a new
list?  For sorting, you definitely need to construct a lookup table
since the sort algorithm needs to look over the indices multiple
times, which means you are using two pointer indirections per index.
Is that cheaper than just copying all the pointers to a new list? Even
if there is any benefit at all, you'll need to implement listagent in
C to squeeze it out.

However, using listagents is faster if you just want a few items out
of the slice. And it's cute.

Peace,
----aht



More information about the Python-list mailing list