'A function that accepts an arbitrary number of lists and returns a single list with exactly one occurrence of each element in python

How to write a function that accepts an arbitrary number of lists and returns a single list with exactly one occurrence of each element that appears in any of the input lists? For example:

 list1 = [1,2,3,1,3,5]
 list2 = [2,3,4,"a","b"]
 list3 = [4,5,6,"b","c]
 # and the result:
 result_list = [1,2,3,4,5,6,"a","b","c"]

I'm looking for a function with perhaps an indefinite number of arguments passed by keyword.



Solution 1:[1]

combine them then make it a set which removes duplicates and then convert it back to a list again

list1 = [1,2,3,1,3,5]
list2 = [2,3,4,'a','b']
list3 = [4,5,6,'b','c']

print(list(set(list1 + list2 + list3)))

If you want it like a function maybe something like this, you can pass in as many lists as you like

def unique_list(*args):
    l = []
    [l.extend(x) for x in args]
    return list(set(l))   

if __name__ == '__main__':
    new_list = unique_list([1,2,3,1,3,5], [2,3,4,'a','b'], [4,5,6,'b','c'])
    print(new_list)

Solution 2:[2]

Try this,

def combine_lists(*argv):
    sum_lst = []
    for lst in argv:
        sum_lst += lst
    return list(set(sum_lst))

Results

In [58]: combine_lists(list1,list2,list3)
Out[58]: ['a', 1, 2, 3, 4, 5, 6, 'c', 'b']
In [59]: combine_lists(list1,list2,list3,list2,list1)
Out[59]: ['a', 1, 2, 3, 4, 5, 6, 'c', 'b']

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2