>> 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*
_______________________________________________
Python-ideas mailing list
[email protected]
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/