Efficient way to union two list with list or None value

Viewed 4092

I have two list that can be list or None. I want to get third list with result of unique unite this two list.

  • If first list is None and second is None - result will be None
  • If first is None and second is not None - result will be second
  • If second is None and first is not None - result will be first
  • If second is not None and first is not None - result will be first + second

I do this simple with if condition:

result = first if first else second
if result is not None:
    try:
        result = list(set(first + second))
    except TypeError:
        pass

            

I want to do this in better way. Maybe you know way to solve this by one or more string using itertools or something else.

2 Answers

A one-liner solution using itertools.chain.from_iterable can be :

set(itertools.chain.from_iterable((first or [], second or [])))

EDIT:

I made some timings of different solutions, here is what I obtain (on my computer, using python3.6), for 10000 iterations for 2 lists of 10000 items :

  • OP way : 7.34 s
  • raw set way (comment from @myaut : set((first or []) + (second or [])) ) : 5.95 s
  • itertools way : 5.69 s

So itertools way is a little bit faster, the chain method is better than the + operator for list :).

Well, I'd be straightforward: if a list is None, replace it with an empty list, then concatenate both:

def concat(l1, l2):
    if l1 is None and l2 is None:
        return None
    elif l1 is None:
        l1 = []
    elif l2 is None:
        l2 = []

    s = set(l1 + l2)

    return  s

Some results:

>>> concat(None, None) is None
True
>>> concat([1,2,3], None)
set([1, 2, 3])
>>> concat(None, [4,5])
set([4, 5])
>>> concat([1,2,3], [4,5])
set([1, 2, 3, 4, 5])
>>> concat([1,2,3], [])
set([1, 2, 3])
>>> concat([], [])
set([])

There are many ways to do it but to me it is the clear case where there is no need to cleverness.

Related