copy list, which way is best? /style
Duncan Booth
duncan at NOSPAMrcp.co.uk
Wed Jul 9 09:06:06 EDT 2003
"Andreas Kuntzagk" <andreas.kuntzagk at mdc-berlin.de> wrote in
news:begt35$4sd5m$1 at fu-berlin.de:
> There are three ways to (shallow)copy a list l I'm aware of:
>
>>>> l2=list(l)
>>>> l2=l[:]
>>>> l2.copy.copy(l)
>
> Are there any differences? Are there more (reasonable) ways?
> I think the first is the most pythonic, second looks more like this other
> p-language and third requires an import, so I would prefer the first.
> Do you agree?
They all do slightly different things.
I think this is a fairly accurate description of what each of these does:
>>> l2 = list(l)
This will copy any iterable object and will produce a new, distinct list as
a result.
>>> l2=l[:]
This will copy a sequence, and will return an object of the same type as
the original. If the original is immutable, then it may simply return the
original object and not bother with making a copy.
>>> l2=copy.copy(l)
This will copy any object whether or not it is a sequence, but it may still
return the original object for immutables.
>>> l2=copy.deepcopy(l)
This will make a deep copy of an object. It only returns the original
object for immutables if any objects they contain are also immutable
(including their contents).
--
Duncan Booth duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?
More information about the Python-list
mailing list