extended slicing for lists

Michael Hudson <mwh21@cam.ac.uk> writes:
Guido van Rossum <guido@beopen.com> writes:
Good idea. Are lists and tuples going to support seq[a:b:c] anytime soon?
It's on my wish list, but can't be done for 2.0.
This would involve the list type implementing the mapping API wouldn't it? This would seem to be a little on the silly side. Never mind; here's a quick-hack patch that "seems to work" for lists: [snip]
I've now put this (or a slightly less buggy version) onto sourceforge. Guido said (after I bothered him in private email) that he'd expect that:
l = range(10) l[2:10:2] = [0]*5 l [0, 1, 0, 3, 0, 5, 0, 7, 0, 9]
And also:
l = range(10) l[4:-1:-1] = range(5) l [4, 3, 2, 1, 0, 5, 6, 7, 8, 9]
(and presumably del l[a:b:c]) Now I'd expect *that* as well, but I was wondering what should happen if the lengths of the lists don't match up ... just bail? That would be easiest, but it doesn't quite gel well with current behaviour for simple slices. Presuming an error, what about these (assuming d is a list of the wrong length): l[a:b:-1] = d l[a:b:1] = d l[a:b:] = d I think these should probably be errors too, but I'd welcome any opinions people have. Cheers, M. -- A witty saying proves nothing. -- Voltaire

On 28 Jul 2000, Michael Hudson wrote:
l = range(10) l[2:10:2] = [0]*5 l [0, 1, 0, 3, 0, 5, 0, 7, 0, 9]
Hmph. I'd be perfectly comfortable with >>> l[2:10:2] = [0]*5 TypeError: lists cannot assign to stepped slices I can't see this being a commonly desired feature. If it were perfectly clear what should happen in all cases, i'd be okay with it -- but the ambiguity you get when the length of the right side doesn't match the length of the indicated slice is sufficient for me to suggest just dropping it: better to avoid confusion altogether.
(and presumably del l[a:b:c])
That seems reasonable and well-defined. A separate question: does l[::-1] return l reversed? That is, are the defaults for omitted start/end exchanged if step is negative? This would seem to be quite useful -- having to say l[len(l)-1:-1:-1] would be a royal pain. -- ?!ng
participants (2)
-
Ka-Ping Yee
-
Michael Hudson