-1

So say you have n numbers in a list as so

[n1, n2, n3, ...., n]

How would you get all possible combinations?

For example if you had

[1,2,3,4]

You return a list like:

[[1,2], [1,3], [1,4], [2,3], [2,4], [3,4], [1,2,3], [1,2,4], [1,3,4], [2, 3, 4], [1,2,3,4]]
  • This might help you: https://stackoverflow.com/questions/464864/how-to-get-all-possible-combinations-of-a-list-s-elements – hitesh bedre Nov 26 '21 at 17:59

1 Answers1

1

Here is a generator function, using the go-to itertools.combinations:

from itertools import combinations

def combos(lst):
    for n in range(2, len(lst)+1):
        yield from combinations(lst, n)

list(combos([1,2,3,4]))
# [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4), 
#  (1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4), 
#  (1, 2, 3, 4)]

If you desperately need lists instead of tuples:

list(map(list, combos([1,2,3,4])))
# [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4], 
#  [1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4], 
#  [1, 2, 3, 4]]
user2390182
  • 72,016
  • 6
  • 67
  • 89