Search code examples
pythonlistpermutation

Permutate two lists but keep index


I want to permutate over all possible combinations of two lists, but I want that each element remains at its index. Here is an example of what I want to achieve.

[1, 2, 3] and [a, b, c] should give: [1, 2, 3], [a, 2, 3], [1, b, 3], [1, 2, c], [a, b, 3], etc.

Is there a neat way to achieve this result?

A normal permutation switches the place of in elements of the list, which is what I want to avoid.


Solution

  • Using itertools.product and zip:

    from itertools import product
    
    list1 = [1, 2, 3]
    list2 = ['a', 'b', 'c']
    
    out = list(product(*zip(list1, list2)))
    

    Output:

    [(1, 2, 3),
     (1, 2, 'c'),
     (1, 'b', 3),
     (1, 'b', 'c'),
     ('a', 2, 3),
     ('a', 2, 'c'),
     ('a', 'b', 3),
     ('a', 'b', 'c')]
    

    If the order is important:

    out = [list(x[::-1]) for x in product(*zip(list1[::-1], list2[::-1]))]
    

    Output:

    
    [[1, 2, 3],
     ['a', 2, 3],
     [1, 'b', 3],
     ['a', 'b', 3],
     [1, 2, 'c'],
     ['a', 2, 'c'],
     [1, 'b', 'c'],
     ['a', 'b', 'c']]