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

Mikhail V mikhailwas at gmail.com
Sun Jun 17 13:01:09 EDT 2018


[by request I've made new subject and summary of proposal]


The idea is to introduce new syntax for the list.append() method.


Syntax:

Variant 1.
Use special case of index, namely omitted index:

    mylist[] = item

Examples:

    mylist = [1, 2, 3]            --> [1, 2, 3]
    mylist[] = x                --> [1, 2, 3, x]
    mylist[] = [foo, bar]        --> [1, 2, 3, [foo, bar]]

instead of current:

    mylist = [1, 2, 3]
    mylist.append(x)
    mylist.append([foo, bar])


Variant 2.
Use one of the augmented assignment operators.
For example using ^= operator:

    mylist = [1, 2, 3]
    mylist ^= x
    mylist ^= [foo, bar]

For example using >>= operator:

    mylist = [1, 2, 3]
    mylist >>= x
    mylist >>= [foo, bar]

Other operators may be considerd as well.



Motivation
-----------

1. Assignment form reduces text amount in statements and makes the right-hand
part, namely the item, clean of additional brackets, which is improtant
especially by more complex items which can also contain brackets or quotes.
For example:

    mylist.append([[foo, bar], [] ])

Could be written as:

    mylist[] = [[foo, bar], [] ]

Which preserves the original item form and has generally more balanced look.


2. Method form has one general issue, especially by longer variable names.
Example from https://docs.python.org/3/tutorial/datastructures.html

    ...
    for row in matrix:
        transposed_row.append (row[i])
    transposed.append (transposed_row)

It becomes hard to read because of lack of spacing between variable names
and list names. With the new syntax it could be written:

    for row in matrix:
        transposed_row[] = row[i]
    transposed[] = transposed_row


3. Item appending is very frequent operation. In current syntax, extend() method
has dedicated syntax.

    mylist1 += mylist2

One of important aspects of proposal is that it should discourage usage of +=
for appending an item. Namely the idea is to discourage this form :

    mylist += [item]

Because it is clunky and may cause additional confusion.
E.g. adding brackets is often used and understood as operation of increasing
dimension of a list - so in case of variable (not literal) the
immediate reaction to
this form is that there might be intention to increase the dimension of list,
and not just create a list from say, an integer.
But of course, increasing the dimension may be also the intention, so this
construct causes extra brain load.


Also in current syntax it is possible to add item to a dictionary with
assignment
statement:

    mydict[key] = item

Despite it is also possible via update() method.

In both cases assignment form gained popularity and used very often.


More information about the Python-ideas mailing list