Best way to create a copy of a list

Frank Millman frank at chagford.com
Tue Apr 4 03:07:53 EDT 2006


Fredrik Lundh wrote:
> Frank Millman wrote:
>
> > I have found two ways of doing it that seem to work.
> >
> > 1 - row = table[23][:]
> >
> > 2 - row = []
> >      row[:] = table[23]
> >
> > Are these effectively identical, or is there a subtle distinction which
> > I should be aware of.
> >
> > I did some timing tests, and 2 is quite a bit faster if 'row'
> > pre-exists and I just measure the second statement.
>
> quite a bit ?  maybe if you're using very short rows, and all rows
> have the same length, but hardly in the general case:
>
> python -mtimeit -s "data=[range(100)]*100; row = []" "row[:] = data[23]"
> 100000 loops, best of 3: 5.35 usec per loop
>
> python -mtimeit -s "data=[range(100)]*100" "row = data[23][:]"
> 100000 loops, best of 3: 4.81 usec per loop
>
> (for constant-length rows, the "row[:]=" form saves one memory
> allocation, since the target list can be reused as is.  for longer rows,
> other things seem to dominate)
>
> </F>

Interesting. My results are opposite.

python -mtimeit -s "data=[range(100)]*100; row = []" "row[:] =
data[23]"
100000 loops, best of 3: 2.57 usec per loop

python -mtimeit -s "data=[range(100)]*100" "row = data[23][:]"
100000 loops, best of 3: 2.89 usec per loop

For good measure, I tried Rune's suggestion -

python -mtimeit -s "data=[range(100)]*100" "row = list(data[23])"
100000 loops, best of 3: 3.69 usec per loop

For practical purposes these differences are immaterial - I do not
anticipate huge quantities of data.

If they are all equivalent from a functional point of view, I lean
towards the second version. I agree with Rune that the third one is
nicer to read, but somehow the [:] syntax makes it a bit more obvious
what is going on.

Thanks

Frank




More information about the Python-list mailing list