0

I have this list:

List = [1, 2, 3]

...and I want to print out all possible combinations such that the output is like:

[1]
[1,2]
[1, 2, 3]
[2]
[2, 3]
[3]

So far my code is this:

E=[]
i=0
for seq in L[i:]:
    E.append(seq)
    i += 1
    print(E)

Which gives my first 3 outputs. Is there a way for me to loop it so that the index goes up by 1 so I can get my desired output?

Edit; so I basically want to write a code which summarizes this:

List = [1, 2, 3]
E = []
F = []
G = []


for seq in List[0:]:
    E.append(seq)
    print(E)

for seq in List[1:]:
    F.append(seq)
    print(F)

for seq in List[2:]:
    G.append(seq)
    print(G)

I pretty much want to know if I can loop the index so that I don't have to create multiple for loops and maybe apply it to a longer list.

desert123
  • 1
  • 1

1 Answers1

0

You are creating combinations of increasing length, so use itertools.combinations() with a length ranging from 1 to len(inputlist):

>>> from itertools import combinations
>>> List = [1, 2, 3]
>>> for i in range(len(List)):
...     for combo in combinations(List, r=i + 1):
...         print(combo)
...
(1,)
(2,)
(3,)
(1, 2)
(1, 3)
(2, 3)
(1, 2, 3)

combinations() produces tuples, but those are trivially converted to lists if you must have a mutable sequence for each.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343