By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,289 Members | 1,342 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,289 IT Pros & Developers. It's quick & easy.

copy list, which way is best? /style

P: n/a
Hi,

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?

Andreas
Jul 18 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
Andreas Kuntzagk wrote:
Hi,

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?

Andreas


The way I'd do it is

from copy import copy
l2 = copy(l1)

or

from copy import deepcopy
l2 = deepcopy(l1)

I don't know what the difference is, if any, but I think this way is more
readable.

HTH,
Andrew Wilkinson

--
Study + Hard Work + Loud Profanity = Good Code
Jul 18 '05 #2

P: n/a
"Andreas Kuntzagk" <an**************@mdc-berlin.de> wrote in
news:be************@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 du****@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?
Jul 18 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.