relative speed of incremention syntaxes (or "i=i+1" VS "i+=1")

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sun Aug 21 21:16:58 EDT 2011


Chris Angelico wrote:

> 2011/8/22 Andreas Löscher <andreas.loescher at s2005.tu-chemnitz.de>:
>> But every improvement on your algorithm will easily result in a
>> significant shorter execution time than replaceing a+=1 with a=a+1 will
>> ever do. :-)
>>
> 
> Agreed. If Python needed a faster alternative to "a=a+1", then I would
> recommend an "a.inc()" call or something; some way to avoid looking up
> the value of 1.

Keep in mind that ints in Python are objects, not memory locations, and can
be shared. If you are hoping for an in-place increment, I invite you to
consider the following code and try to predict what it would do:

a = 42
b = a
b.inc()
print(a)



-- 
Steven




More information about the Python-list mailing list