Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

list comprehension question

Is there a way to add multiple items to a list in a list comprehension per iteration? For example:

y = ['a', 'b', 'c', 'd']
x = [1,2,3]

return [x, a for a in y]

output: [[1,2,3], 'a', [1,2,3], 'b', [1,2,3], 'c', [1,2,3], 'd']

like image 607
Falmarri Avatar asked Nov 27 '10 01:11

Falmarri


2 Answers

sure there is, but not with a plain list comprehension:

EDIT: Inspired by another answer:

y = ['a', 'b', 'c', 'd']
x = [1,2,3]

return sum([[x, a] for a in y],[])

How it works: sum will add a sequence of anythings, so long as there is a __add__ member to do the work. BUT, it starts of with an initial total of 0. You can't add 0 to a list, but you can give sum() another starting value. Here we use an empty list.

If, instead of needing an actual list, you wanted just a generator, you can use itertools.chain.from_iterable, which just strings a bunch of iterators into one long iterator.

from itertools import *

return chain.from_iterable((x,a) for a in y)

or an even more itertools friendly:

return itertools.chain.from_iterable(itertools.izip(itertools.repeat(x),y))

There are other ways, too, of course: To start with, we can improve Adam Rosenfield's answer by eliminating an unneeded lambda expression:

return reduce(list.__add__,([x, a] for a in y))

since list already has a member that does exactly what we need. We could achieve the same using map and side effects in list.extend:

l = []
map(l.extend,[[x, a] for a in y])
return l

Finally, lets go for a pure list comprehension that is as inelegant as possible:

return [ y[i/2] if i%2 else x for i in range(len(y)*2)]
like image 195
SingleNegationElimination Avatar answered Oct 09 '22 23:10

SingleNegationElimination


Here's one way:

y = ['a', 'b', 'c', 'd']
x = [1,2,3]

return reduce(lambda a,b:a+b, [[x,a] for a in y])
like image 42
Adam Rosenfield Avatar answered Oct 09 '22 23:10

Adam Rosenfield