which methods to use?

s99999999s2003 at yahoo.com s99999999s2003 at yahoo.com
Thu Mar 29 03:40:20 EDT 2007


On Mar 29, 12:56 pm, Steven D'Aprano
<s... at REMOVE.THIS.cybersource.com.au> wrote:
> 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.


hi thanks
under what circumstances do we need to create a copy of a tuple :->
"btuple = atuple[:]". tuples are immutable, so wouldn't it be "wasting
memory"?
another query, in the docs, list(a) and a[:] does the same thing (a =
[1,2,3] for example), but besides the speed of slicing is faster than
list(), what advantage is there for using list(a) in this case ?
thanks




More information about the Python-list mailing list