Best way to create a copy of a list

Rune Strand rune.strand at gmail.com
Tue Apr 4 02:27:00 EDT 2006


Frank Millman wrote:
> Hi all
>
> Assume a 2-dimensional list called 'table' - conceptually think of it
> as rows and columns.
>
> Assume I want to create a temporary copy of a row called 'row',
> allowing me to modify the contents of 'row' without modifying the
> contents of 'table'.
>
> I used to fall into the newbie trap of 'row = table[23]', but I have
> learned my lesson by now - changing 'row' also changes 'table'.
>
> 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.


you could use list()

row = list(table[23])

The effect is the same, but it's nicer to read.
See also the copy module.




More information about the Python-list mailing list