Search code examples
pythonpython-itertools

List with non-repeating sublists from given list


How to create a list with n-size non-repeating sublists from given list? I think the example will explain a lot.

given_list = [1, 2, 3, 4, 5]
n = 3
desired_list = [[1,2,3], [1,2,4], [1,2,5], [1,3,4], [1,3,5], [1,4,5], [2,3,4], [2,3,5], [2,4,5], [3,4,5]]

EDIT: I forgot to add some important combinations


Solution

  • Not sure if you want combinations or permutations, so here are both:

    Permutations

    You can use permutations from itertools to find all permutations of a given list:

    from itertools import permutations
    
    given_list = [1, 2, 3, 4, 5]
    n = 3
    
    print([list(i) for i in permutations(given_list, n)])
    

    Output:

    [[1, 2, 3], [1, 2, 4], [1, 2, 5], [1, 3, 2], [1, 3, 4], [1, 3, 5], [1, 4, 2], [1
    , 4, 3], [1, 4, 5], [1, 5, 2], [1, 5, 3], [1, 5, 4], [2, 1, 3], [2, 1, 4], [2, 1
    , 5], [2, 3, 1], [2, 3, 4], [2, 3, 5], [2, 4, 1], [2, 4, 3], [2, 4, 5], [2, 5, 1
    ], [2, 5, 3], [2, 5, 4], [3, 1, 2], [3, 1, 4], [3, 1, 5], [3, 2, 1], [3, 2, 4],
    [3, 2, 5], [3, 4, 1], [3, 4, 2], [3, 4, 5], [3, 5, 1], [3, 5, 2], [3, 5, 4], [4,
     1, 2], [4, 1, 3], [4, 1, 5], [4, 2, 1], [4, 2, 3], [4, 2, 5], [4, 3, 1], [4, 3,
     2], [4, 3, 5], [4, 5, 1], [4, 5, 2], [4, 5, 3], [5, 1, 2], [5, 1, 3], [5, 1, 4]
    , [5, 2, 1], [5, 2, 3], [5, 2, 4], [5, 3, 1], [5, 3, 2], [5, 3, 4], [5, 4, 1], [
    5, 4, 2], [5, 4, 3]]
    

    Combinations

    And you can use combinations from itertools to find all the combinations of a given list:

    from itertools import combinations
    
    given_list = [1, 2, 3, 4, 5]
    n = 3
    
    print([list(i) for i in combinations(given_list, n)])
    

    Output:

    [[1, 2, 3], [1, 2, 4], [1, 2, 5], [1, 3, 4], [1, 3, 5], [1, 4, 5], [2, 3, 4], [2
    , 3, 5], [2, 4, 5], [3, 4, 5]]