which methods to use?
Alex Martelli
aleax at mac.com
Thu Mar 29 03:44:10 EDT 2007
Steven D'Aprano <steve at REMOVE.THIS.cybersource.com.au> wrote:
...
> 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.
Personally, I don't like the looks of:
newlist = oldlist[:]
It's always looked more like Perl than Python to me. I prefer:
newlist = list(oldlist)
There may be a small performance hit (since Python must lookup the name
'list') but it's typically not important (save in extreme
bottlenecks:-). It's way faster than copy.copy(oldlist), anyway:-)
I particularly like the way "calling the type for shallow copies" is
conceptually uniform across types, e.g.:
newlist = list(oldlist)
newdict = dict(olddict)
newtuple = tuple(oldtuple)
newset = set(oldset)
versus the mishmash one gets by using slicing for the sequences and
.copy() for the dict and set.
A matter of purely stylistic importance, of course.
Alex
More information about the Python-list
mailing list