Python: Combining two lists and removing duplicates in a functional programming way
<p>I'm trying to write a function that would combine two lists while removing duplicate items, but in a pure functional way.
For example:</p>

<pre><code>a = [1,2,2]
b = [1,3,3,4,5,0]
union(a,b) --&gt; [1,2,3,4,5,0]
</code></pre>

<p>The imperative form of the code would be:</p>

<pre><code>def union(a,b):
    c = []
    for i in a + b:
        if i not in c:
            c.append(i)
    return c
</code></pre>

<p>I've tried several approaches, but couldn't find a way to do that without using a loop to go over the items - what am I missing?</p>

<p>To combine the two lists:</p>

<pre><code>a = [1,2,2]
b = [1,3,3,4,5,0]
</code></pre>

<p>Using sets:</p>

<pre><code>union = set(a) | set(b)
# -&gt; set([0, 1, 2, 3, 4, 5])
</code></pre>

<p>Using comprehension list:</p>

<pre><code>union = a + [x for x in b if x not in a]
# -&gt; [1, 2, 2, 3, 3, 4, 5, 0]
</code></pre>

<p>Using loop, without duplicates, preserving order:</p>

<pre><code>union = []
for x in a + b:
    if x not in union:
        union.append(x)
# -&gt; [1, 2, 3, 4, 5, 0]
</code></pre>

python functional-programming