[SciPy-user] help with list comprehensions

Robert Kern robert.kern@gmail....
Wed Aug 1 14:01:35 CDT 2007

Stephen Yang wrote:
> Hello everyone,
> I have a question about list comprehensions. I would like to append data 
> to an existing list using a list comprehension. Unfortunately, what I 
> have tried does not seem to work:
>  >>> y = [5, 1, 3, 5]
>  >>> x = ['a', 'b']
>  >>> new = [x.append(data) for data in y]
>  >>> new
> [None, None, None, None]
> Can anyone help? Thanks very much in advance.

For the example you give, you shouldn't use a list comprehension at all:


If you do need a list comprehension for something more complicated (say, because
you were calling a function on each element):

  x.extend([f(data) for data in y])

The reason that your code didn't do what you thought it did stems from two causes:

  1) list.append() returns None.
  2) You were looking at `new` which was simply the result of the list
comprehension and not `x`, the list you were trying to extend. If you had looked
at `x`, you would have seen that the data were correctly appended. However, you
shouldn't do it that way anyways.

Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

More information about the SciPy-user mailing list