Falmarri
Falmarri

Reputation: 48559

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']

Upvotes: 5

Views: 438

Answers (3)

SingleNegationElimination
SingleNegationElimination

Reputation: 156138

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)]

Upvotes: 6

nate c
nate c

Reputation: 9005

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

[z.extend([x, a]) for a in y]

(The correct value will be in z)

Upvotes: 1

Adam Rosenfield
Adam Rosenfield

Reputation: 400164

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])

Upvotes: 1

Related Questions