3

I saw this solution for merging lists such as a = [1,2,3], b = [4,5,6] using res = [*a, *b].

Assuming I have a list of sub-lists such as ls = [a,b] is it possible to do something like res = [*i for i in ls]?

That specific line is invalid since SyntaxError: iterable unpacking cannot be used in comprehension. Can something similar be done?

If not, How can I create easily a list that contains all elements in sub-lists?

using python 3.5.3

Community
  • 1
  • 1
CIsForCookies
  • 12,097
  • 11
  • 59
  • 124
  • 2
    That syntax works for python3.6 – cs95 Aug 22 '17 at 11:37
  • 2
    @cᴏʟᴅsᴘᴇᴇᴅ Got the same error with python3.6.1 – araknoid Aug 22 '17 at 11:39
  • 1
    @araknoid I'm taking about `[*a, *b]` – cs95 Aug 22 '17 at 11:40
  • @cᴏʟᴅsᴘᴇᴇᴅ Oh, my fault. Thanks that you have specified it in the answer. – araknoid Aug 22 '17 at 11:42
  • @MSeifert I think it's not dup since I ask specifically about `[*i for i in ls]` where the _Making..._ is asking about `reduce` even though we both ask for a solution to the same problem – CIsForCookies Aug 22 '17 at 11:48
  • 1
    In that case, I think the title needed a little more clarification. I've taken the liberty to edit it. – cs95 Aug 22 '17 at 11:50
  • If you're just asking about the `[*i for i in ls]` you may want to drop the part where you ask about "If not, How can I create easily a list that contains all elements in sub-lists?" because that's clearly answered in the dupe. – MSeifert Aug 22 '17 at 11:52

1 Answers1

6

No, I don't believe they've added support for list unpacking inside a comprehension yet.

As an alternative, you can use itertools.chain:

>>> from itertools import chain
>>> list(chain.from_iterable([a, b]))
[1, 2, 3, 4, 5, 6]

Or, a nested loop list comprehension:

>>> [y for x in [a, b] for y in x]
[1, 2, 3, 4, 5, 6]
cs95
  • 379,657
  • 97
  • 704
  • 746