On copying arrays

Duncan Booth duncan.booth at invalid.invalid
Mon Mar 24 05:52:21 EDT 2008


ernesto.adorio at gmail.com wrote:

> Is there a conceptual difference between
>     best =test[:]
> and
>    best = [x for x in test] ?
> test is a list of real numbers. Had to use the second form to avoid a
> nasty bug
> in a program I am writing. I have to add too that I was using psyco
> in Python 2.5.1.
> 
The first one will only copy sliceable sequences and will give you a result 
of the same type as test (e.g. if test is a tuple so is best).

The second one will copy any sequence, always results in a list and as a 
side effect assigns a value to 'x'.

The method usually recommended is:

  best = list(test)

as it has no side effects, copies any sequence and may be faster than the 
list comprehension. As with the second of your examples it always gives you 
a list.



More information about the Python-list mailing list