Union of two lists in Python

Perform a union, keeping repetition:

>>> c = a + b
[1, 2, 2, 3, 2, 5, 6]

Perform a union, keeping repetition & order:

>>> c = sorted(a + b)
[1, 2, 2, 2, 3, 5, 6]

Perform an union, no repetition in each list, but repetition allowed in final union, and keeped order:

>>> c = sorted(list(set(a)) + list(set(b)))
[1, 2, 2, 3, 5, 6]

After clarification of the question, the goal is to build a list that take elements (including repetition) of, and then add elements of b if they are not in the new list.

>>> c = a + [e for e in b if e not in a]
[1, 2, 2, 2, 3, 5, 6]

After another clarification of the question, the goal is to build a list containing all elements of input list. But, if elements are in common, they are pushed the same number there

>>> from collections import Counter
>>> def merge(a,b):
...   na, nb = Counter(a), Counter(b)
...   return list(Counter({k: max((na[k], nb[k])) for k in set(a + b)}).elements())
>>> merge([1, 2, 2, 2, 3], [2, 5, 6])
[1, 2, 2, 2, 3, 5, 6]
>>> merge([1, 2, 3], [2, 2, 4])
[1, 2, 2, 4]

Leave a Comment