-1

Consider following code:

string = "ABCD"
variations = [list(itertools.combinations(string,x)) for x in range(1,5)]
variations

It produces following output:

[[('A',), ('B',), ('C',), ('D',)],
 [('A', 'B'), ('A', 'C'), ('A', 'D'), ('B', 'C'), ('B', 'D'), ('C', 'D')],
 [('A', 'B', 'C'), ('A', 'B', 'D'), ('A', 'C', 'D'), ('B', 'C', 'D')],
 [('A', 'B', 'C', 'D')]]

But the output I would like is:

[('A',),
 ('B',),
 ('C',),
 ('D',),
 ('A', 'B'),
 ('A', 'C'),
 ('A', 'D'),
 ('B', 'C'),
 ('B', 'D'),
 ('C', 'D'),
 ('A', 'B', 'C'),
 ('A', 'B', 'D'),
 ('A', 'C', 'D'),
 ('B', 'C', 'D'),
 ('A', 'B', 'C', 'D')]

In other words, I want to unpack all the data in the sublists into one list (in the shortest way possible)

I've tried to use asterisk:

string = "ABCD" 
variations = [*list(itertools.combinations(string,x)) for x in range(1,5)]

But it throws following error:

SyntaxError: iterable unpacking cannot be used in comprehension

What should I do? (Again, I would like to keep things concise)

iwbtrs
  • 358
  • 4
  • 13

3 Answers3

3

Just add another for to your list comprehension that loops over the combinations:

variations = [y for x in range(1, 5) for y in itertools.combinations(string, x)]
print(variations)

Output:

[('A',), ('B',), ('C',), ('D',), ('A', 'B'), ('A', 'C'), ('A', 'D'), ('B', 'C'), ('B', 'D'), ('C', 'D'), ('A', 'B', 'C'), ('A', 'B', 'D'), ('A', 'C', 'D'), ('B', 'C', 'D'), ('A', 'B', 'C', 'D')]
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
3

You can perform a nested iteration inside the list comprehension. Something like this:

[y for x in range(1,5) for y in itertools.combinations(string, x)]
khelwood
  • 55,782
  • 14
  • 81
  • 108
0

variations = [e for x in range(1,5) for e in (itertools.combinations(string,x)) ]

a_r
  • 488
  • 6
  • 12