[SciPy-user] help with list comprehensions

Ryan May rmay at ou.edu
Wed Aug 1 14:58:42 EDT 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]
> 

I'm not sure if this is just due to your example, but what you really
want to do is:

>>> x.extend(y)

Which will get you the original list x with all of the entries of y
appended.

FYI, if you look at x after running your original code, it's correct.
The problem is that x.append() modifies x in place, and therefore
doesn't return a value, so None gets put into the list "new" for each
item in y.

Ryan

-- 
Ryan May
Graduate Research Assistant
School of Meteorology
University of Oklahoma



More information about the SciPy-User mailing list