[Python-ideas] Where did we go wrong with negative stride?

Andrew Barnert abarnert at yahoo.com
Tue Oct 29 01:14:00 CET 2013


On Oct 28, 2013, at 16:51, Ron Adam <ron3200 at gmail.com> wrote:

> We also need to remember that slicing is also used for inserting things.
> 
> >>> a = list("python")
> >>> b = list("PYTHON")
> >>> a[::2] = b[::2]
> >>> a
> ['P', 'y', 'T', 'h', 'O', 'n']

I was about to write the same thing. Half the mails so far have said things like "you don't need to do [i: j:k] because you can do [m:n:o][::p]". But that doesn't work with assignment; you're just assigning to the temporary copy of the first slice.

And I think people will be bitten by that. People are _already_ bitten by that today, because they saw somewhere on StackOverflow that foo[i:j][::-1] is easier to understand than foo[j+1:i+1:-1] and tried to assign to it (presumably on the assumption that index and slice assignment must work like C++ and other languages that return "references" to the values that can be assigned into) and don't understand why it had no effect.

Today, people who ask this question are opening a useful door. You can explain to them exactly what slicing does, including how __setitem__ works, and they come out of it knowing how to assign to the range that they wanted.

Never mind that these people have no real need for what they're writing and are just screwing around with language features because it's neat; we don't want to say that anyone who learns that way shouldn't be learning Python, do we?

Anyway, a change that makes it impossible to assign to the range looks like a hole in the language. All you can say is that if you wanted to get the slice you could rewrite it this way, but there's no way to rewrite it in terms of setting a slice, but don't worry, we're pretty sure you'll never need to.


More information about the Python-ideas mailing list