[Python-ideas] Alternative spelling for list.append()

Chris Angelico rosuav at gmail.com
Sun Jun 17 21:12:43 EDT 2018


On Mon, Jun 18, 2018 at 10:50 AM, Steven D'Aprano <steve at pearwood.info> wrote:
>> (It's also worth noting that the @ operator is unique in being created
>> solely for the benefit of third-party types. Every other operator is
>> supported by the core types - usually by many of them.
>
> That's not quite correct: although it isn't strictly speaking an
> operator, extended slice notation x[a:b:c] was invented for numpy, and
> for a while (Python 1.4 I think?) no core type supported it.
>
> Similarly for using Ellipsis ... in slices. As far as I know, there is
> still no core type which supports that.

Ellipsis is now just a special form of literal, so it's no longer
magical in any way (there's no difference between x[...] and x(...) in
the syntax). Extended slice notation - interesting that no core type
supported it originally. But, again, both of them are implemented
using a standard protocol: an object represents the entire thing
between the brackets, and that object is passed to __getitem__. So
this might need a new object meaning "emptiness", or else it is
defined that x[]=y is the same as x[None]=y, which would have
confusing implications.

Actually, maybe the problem here is that there's no easy way to
represent "-0" in a slice. Consider:

>>> items = ["spam", "ham", "foo", "bar", "quux"]
>>> items[0] # take first item
'spam'
>>> items[1] # index from start, not at start
'ham'
>>> items[-1] # take last item
'quux'
>>> items[-2] # index from end, not last
'bar'

Indexing is perfectly parallel, as long as you understand that "-2"
mirrors "1". In fact, we could write these using boolean Not, if we
wanted to.

>>> items[~0] # last item
'quux'
>>> items[~1] # second-last item
'bar'

Slicing from the beginning works tidily too.

>>> items[:1] # slice from start to position
['spam']
>>> items[:2] # slice from start to position
['spam', 'ham']
>>> items[:0] # useless in retrieval
[]
>>> items[:0] = ["shim"] # insert at beginning
>>> items
['shim', 'spam', 'ham', 'foo', 'bar', 'quux']
>>> del items[0]

Great. Now let's try slicing from the end:

>>> items = ["spam", "ham", "foo", "bar", "quux"]
>>> items[-1:] # slice from position to end
['quux']
>>> items[-0:] # failed parallel
['spam', 'ham', 'foo', 'bar', 'quux']

So you use -1 in slices to parallel 1 (unlike using ~1 as with
indexing), and everything works *except zero*. Which means that the
slice-assignment form of insert is easy to write, but the
slice-assignment form of append isn't.

Mikhail, if it were possible to append using slice assignment, would
that meet the case?

ChrisA


More information about the Python-ideas mailing list