copy list, which way is best? /style

  • Thread starter Andreas Kuntzagk
  • Start date
A

Andreas Kuntzagk

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
 
A

Andrew Wilkinson

Andreas said:
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
 
D

Duncan Booth

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:
This will copy any iterable object and will produce a new, distinct list as
a result.
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.
This will copy any object whether or not it is a sequence, but it may still
return the original object for immutables.
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).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,575
Members
45,054
Latest member
LucyCarper

Latest Threads

Top