which is more pythonic/faster append or +=[]

kyosohma at gmail.com kyosohma at gmail.com
Wed May 9 15:31:01 EDT 2007


On May 9, 11:08 am, 7stud <bbxx789_0... at yahoo.com> wrote:
> On May 8, 11:05 pm, a... at mac.com (Alex Martelli) wrote:
>
>
>
> > alf <ask at me> wrote:
> > > two ways of achieving the same effect
>
> > > l+=[n]
>
> > > or
>
> > > l.append(n)
>
> > > so which is more pythonic/faster?
>
> > .append - easy to measure, too:
>
> > brain:~ alex$ python -mtimeit 'L=range(3); n=23' 'x=L[:]; x.append(n)'
> > 1000000 loops, best of 3: 1.31 usec per loop
>
> > brain:~ alex$ python -mtimeit 'L=range(3); n=23' 'x=L[:]; x+=[n]'
> > 1000000 loops, best of 3: 1.52 usec per loop
>
> > Alex
>
> Ah, I see.  The list would grow too large with all that appending, so
> you begin again with the original list for every loop.
>
> Is there any documentation for the syntax you are used with timeit?  I
> checked 'man python', and I also read the example in the python docs,
> but  you seem to be using a hybrid syntax.
>
> Thanks.

If you want to have multiple statements on one line, all you need to
do is add the semi-colon. That is what Alex did. I think I saw that
trick in the book "Programming Python" by Lutz...or some other
reference text. Here's one link to the anomaly:
http://safari.oreilly.com/0201748843/ch07lev1sec5

Here's another link that mentions it as well:
http://www-128.ibm.com/developerworks/opensource/library/os-python5/

Mike




More information about the Python-list mailing list