Search code examples
pythonlisttuplescombinations

Given a List get all the combinations of tuples without duplicated results


I have a list=[1,2,3,4] And I only want to receive tuple results for like all the positions in a matrix, so it would be

(1,1),(1,2),(1,3),(1,4),(2,1),(2,2),(2,3),(2,4),(3,1),(3,2),(3,3),(3,4),(4,1),(4,2),(4,3),(4,4)

I've seen several codes that return all the combinations but i don't know how to restrict it only to the tuples or how to add the (1,1),(2,2),(3,3),(4,4)

Thank you in advance.


Solution

  • You just need a double loop. A generator makes it easy to use

    lst = [1,2,3,4]
    
    def matrix(lst):
        for i in range(len(lst)):
            for j in range(len(lst)):
                yield lst[i], lst[j]
    
    output = [t for t in matrix(lst)]
    
    print(output)
    

    Output:

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