stupid/style/list question

Tim Chase python.list at tim.thechases.com
Tue Jan 8 10:53:07 EST 2008


> To flush a list it is better doing "del mylist[:]" or "mylist = []"?
> Is there a preferred way? If yes, why?

It depends on what you want.  The former modifies the list
in-place while the latter just reassigns the name "mylist" to
point to a new list within the local scope as demonstrated by this:

  def d1(mylist):
    "Delete in place"
    del mylist[:]

  def d2(mylist):
    "Just reassign"
    mylist = []

  for test in [d1,d2]:
    input = [1,2,3]
    print 'Before:', input
    print test.__doc__
    test(input)
    print 'After:', input
    print

As performance goes, you'd have to test it, but I suspect it's
not a glaring difference, and would suspect that the latter is a
bit faster.


-tkc





More information about the Python-list mailing list