which methods to use?

Steven D'Aprano steve at REMOVE.THIS.cybersource.com.au
Thu Mar 29 06:56:15 CEST 2007


On Wed, 28 Mar 2007 18:16:31 -0700, s99999999s2003 wrote:

> what do you mean by create new object when using list comprehensoin or
> list()? Does using slicing create a new object as well?

Yes it does.

>>> alist = [1, 2, 4, 8, 16]
>>> blist = alist # not a copy
>>> id(alist) == id(blist)
True
>>> blist = alist[:] # a copy
>>> id(alist) == id(blist)
False

By the way, "id(obj) == id(another_object)" is just a long way of writing
"obj is another_object".

In general:

- use a list comprehension when you need to calculate the list items

- use slicing when you are copying an actual list, or if you don't care
what type of object you get

- use the list() function when your existing object might not be an actual
list, and you want the copy to be a list.

E.g.

atuple = (1, 2, 3)
alist = [2*n+3 for n in atuple]
btuple = atuple[:]
blist = list(atuple)



-- 
Steven.




More information about the Python-list mailing list