Producing multiple items in a list comprehension

Peter Otten __peter__ at web.de
Thu May 22 15:13:36 EDT 2008


Joel Koltner wrote:

> Is there an easy way to get a list comprehension to produce a flat list
> of, say, [x,2*x] for each input argument?
> 
> E.g., I'd like to do something like:
> 
> [ [x,2*x] for x in range(4) ]
> 
> ...and receive
> 
> [ 0,0,1,2,2,4,3,6]
> 
> ...but of course you really get a list of lists:
> 
> [[0, 0], [1, 2], [2, 4], [3, 6]]
> 
> I'm aware I can use any of the standard "flatten" bits of code to turn
> this back into what I want, but I was hoping there's some way to avoid the
> "lists of lists" generation in the first place?


>>> [x*y for x in range(4) for y in 1,2]
[0, 0, 1, 2, 2, 4, 3, 6]


> A slightly similar problem: If I want to "merge," say, list1=[1,2,3] with
> list2=[4,5,6] to obtain [1,4,2,5,3,6], is there some clever way with "zip"
> to do so?

>>> items = [None] * 6
>>> items[::2] = 1,2,3
>>> items[1::2] = 4,5,6
>>> items
[1, 4, 2, 5, 3, 6]

Peter



More information about the Python-list mailing list