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']
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
sure there is, but not with a plain list comprehension:
EDIT: Inspired by another answer:
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 givesum()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.or an even more itertools friendly:
There are other ways, too, of course: To start with, we can improve Adam Rosenfield’s answer by eliminating an unneeded lambda expression:
since list already has a member that does exactly what we need. We could achieve the same using
mapand side effects inlist.extend:Finally, lets go for a pure list comprehension that is as inelegant as possible: