"Canonical" way of deleting elements from lists

Nick Craig-Wood nick at craig-wood.com
Wed Jan 9 07:30:05 EST 2008


Robert Latest <boblatest at yahoo.com> wrote:
>  Hrvoje Niksic wrote:
> 
> > keywords[:] = (s for s in keywords if s)
> 
>  Looks good but is so far beyond my own comprehension that I don't dare 
>  include it in my code ;-)

:-)  Worth understanding thought I think - here are some hints

  keywords[:] = (s for s in keywords if s)

is equivalent to this (but without creating a temporary list)

  keywords[:] = list(s for s in keywords if s)

which is equivalent to

  keywords[:] = [s for s in keywords if s]

This

  keywords[:] = ....

Replaces the contents of the keywords list rather than making a new
list.

Here is a demonstration of the fundamental difference

  >>> a=[1,2,3,4]
  >>> b=a
  >>> a=[5,6,7]
  >>> print a, b
  [5, 6, 7] [1, 2, 3, 4]

  >>> a=[1,2,3,4]
  >>> b=a
  >>> a[:]=[5,6,7]
  >>> print a, b
  [5, 6, 7] [5, 6, 7]

Using keywords[:] stops the creation of another temporary list.  The
other behaviour may or may not be what you want!

-- 
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick



More information about the Python-list mailing list