Search code examples
pythontuples

How to combine list of objects into list of tuples (matrix style) in Python?


Let's say that I have a list of tuples foo (object, integer) and a list of objects bar. The length of each of these parent lists is variable. How do I combine them into a single list of tuples, wherein each tuple is a unique combination of elements from each of the two parent lists?

  • Example 1:

    foo = [(A, i)]
    bar = [X, Y]
    # missing magic
    expected_result = [(A, i, X), (A, i, Y)]
    
  • Example 2:

    foo = [(A, i), (B, j)]
    bar = [X, Y]
    # missing magic
    expected_result = [(A, i, X), (A, i, Y), (B, j, X), (B, j, Y)]
    
  • Example 3:

    foo = [(A, i), (B, j), (C, k)]
    bar = [X, Y]
    # missing magic
    expected_result = [(A, i, X), (A, i, Y), (B, j, X), (B, j, Y), (C, k, X), (C, k, Y)]
    
  • Example 4:

    foo = [(A, i), (B, j)]
    bar = [X]
    # missing magic
    expected_result = [(A, i, X), (B, j, X)]
    

Preferably, I'd like to do this in one line, if possible. The order of the resulting list is unimportant, but the order of the elements within the tuples of that list need to be predictable.

In addition to trying various solutions using itertools.product and zip, I also looked at the answers to other similar questions, but I was unable to find the solution to this problem.


Solution

  • Your case is indeed tricky, and zip or itertools.product do not directly do the job, since you want to concatenate a tuple and an element into a tuple with all elements. In one line, you can use unpacking:

    expected_result = [(*i, j) for i in foo for j in bar]
    

    Assuming, as in your example, that foo is a list of tuples and bar is a list of elements.