Search code examples
pythonpython-itertools

Python list combination


I have a list:

nums = [1, 2, 3, 4]

I'd like to get all the possibilities to split the list 1 - 3:

[
    ( 1, (2, 3, 4) ),
    ( 2, (1, 3, 4) ),
    ( 3, (1, 2, 4) ),
    ( 4, (1, 2 ,3) )
]

Now the best I can find is use itertools.combinations(num, 3), but it will only give the second part of each item, that means [(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]. are there other methods I can use?


Solution

  • Depending on how general the problem you're solving is, the solution can be more or less simple :)

    In [1]: nums = [1, 2, 3, 4]
    
    In [2]: [(x, tuple(y for y in nums if y != x)) for x in nums]
    Out[2]: [(1, (2, 3, 4)), (2, (1, 3, 4)), (3, (1, 2, 4)), (4, (1, 2, 3))]
    

    If there are repeating values in the list, use indices for comparison:

    In [3]: [(x, tuple(y for j, y in enumerate(nums) if j != i)) for i, x in enumerate(nums)]
    Out[3]: [(1, (2, 3, 4)), (2, (1, 3, 4)), (3, (1, 2, 4)), (4, (1, 2, 3))]