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

Juancarlo Añez apalala at gmail.com
Mon Jun 18 21:20:25 EDT 2018


>> For all practical purpose, it would be enough to define that the
>> expression:
>>
>> mylist += [item]
>>
>> gets optimized to mylist.append(item).
>>
>
> Unfortunately, that would create yet another special case of operators
> breaking the rules. Most operators invoke magic methods. This would prevent
> ``+=`` from invoking ``__iadd__`` for lists, since the right-hand side
> would need to be compiled differently. It's similar to why ``and`` and
> ``or`` keywords can't have magic methods.
>

It seems that the optimization is already in place:

import timeit

COUNT = 10000
REPS = 10000

def using_append():
    result = []
    for i in range(COUNT):
        result.append(i)
    return result


def using_concat():
    result = []
    for i in range(COUNT):
        result += [i]
    return result


def using_iadd():
    result = []
    for i in range(COUNT):
        result.__iadd__([i])
    return result


def main():
    print(timeit.timeit('using_append()', globals=globals(), number=REPS))
    print(timeit.timeit('using_concat()', globals=globals(), number=REPS))
    print(timeit.timeit('using_iadd()', globals=globals(), number=REPS))



if __name__ == '__main__':
    main()


-- 
Juancarlo *Añez*
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20180618/bee2e804/attachment-0001.html>


More information about the Python-ideas mailing list