-1

Say I have a list

my_input_list = [22,33,56,1]

and from a variable target_len I want to make (exclusive, sorted) sublists of that length

target_len = 2
#my_output_list_not_sorted = [[22,33][22,56][22,1][33,56][33,1][56,1]]
my_output_list = [[22,33][22,56][1,22][33,56][1,33][1,56]]

or

target_len = 3
#my_output_list_not_sorted = [[[22,33,56][22,33,1][33,56,1]]
my_output_list = [[22,33,56][1,22,33][1,33,56]]

Is there a neat way to do this?

I'm OK to sort my_input_list first if needed.

Thanks!

Joylove
  • 414
  • 1
  • 5
  • 20

1 Answers1

2

Looks like you need itertools.combinations

import itertools
my_input_list = [22,33,56,1]
target_len = 2
print([sorted(x) for x in itertools.combinations(my_input_list, target_len)])

Output:

[[22, 33], [22, 56], [1, 22], [33, 56], [1, 33], [1, 56]]
Rakesh
  • 81,458
  • 17
  • 76
  • 113