Python 3.3 function to merge unique values form multiple lists to one list

user2243215 picture user2243215 · Apr 4, 2013 · Viewed 12.2k times · Source

I am pretty new to Python..I am trying to write a function that will merge unique values in separate lists into one list. I keep getting a result of a tuple of lists. Ultimately I would like to have one list of unique values from my three lists -a,b,c. Can anyone give me a hand with this?

def merge(*lists):
    newlist = lists[:]
    for x in lists:
        if x not in newlist:
            newlist.extend(x)
    return newlist

a = [1,2,3,4]
b = [3,4,5,6]
c = [5,6,7,8]

print(merge(a,b,c))

I am getting a Tuple of Lists

([1, 2, 3, 4], [3, 4, 5, 6], [5, 6, 7, 8])

Answer

g.d.d.c picture g.d.d.c · Apr 4, 2013

You may just need sets:

>>> a = [1,2,3,4]
>>> b = [3,4,5,6]
>>> c = [5,6,7,8]
>>>
>>> uniques = set( a + b + c )
>>> uniques
set([1, 2, 3, 4, 5, 6, 7, 8])
>>>