Search code examples
pythonperformanceset-union

Form the sequence of a union of two sets efficiently


Dear Reader of this post,

do you have an idea how to form the sequence of a union of two lists efficiently in Python? Suppose there are the two following lists:

 list_a = [['a','b'],['a','c'],['b','c']]
 list_b = ['h','i']

and I want to calculate:

 new_list = [['a','b','h'],['a','b','i'],['a','c','h'],['a','c','i'],['b','c','h'],
             ['b','c','i']].

Up to now, I am using the following loops:

        new_list = [r+[j] for j in list_b for r in list_a]

However, I find this ugly. I do not like the two loops. I prefer using functions instead.

Do you have another idea to achieve the desired task? (Among other things, I tried to follow this Get the cartesian product of a series of lists in Python suggestion, but to no avail.)

I am grateful for any suggestions!

Best regards, Fabian


Solution

  • You could use itertools.product:

    [a+[b] for a, b in itertools.product(list_a, list_b)]
    

    However, there's nothing really wrong with the way you did it. Using two loops in a list comprehension is fine if you really need to get every combination of elements from both iterables. The product solution, though, does have the advantage that it is more easily extended to more iterables (e.g., it's easy to get every combination of three or four or ten lists, whereas deeply nested loops can become cumbersome).