Best way to create a copy of a list

Fredrik Lundh fredrik at pythonware.com
Tue Apr 4 02:33:31 EDT 2006


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>






More information about the Python-list mailing list