2

my problem is the following:

for a given list of length L for example (L=4):

["a","b","c","d"]

i would like to obtain all the possible "sublist" of lenght X of this list while keeping the order of the elements. for X=2 it would return me:

["a","b"]
["a","c"]
["a","d"]
["b","c"]
["b","d"]
["c","d"]

I don't really know how to start, any help would be appreciated

Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91

1 Answers1

2

You can use itertools.combinations for the task:

from itertools import combinations

lst = ["a", "b", "c", "d"]
X = 2

for c in combinations(lst, X):
    print(list(c))

Prints:

['a', 'b']
['a', 'c']
['a', 'd']
['b', 'c']
['b', 'd']
['c', 'd']
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91