DanH
DanH

Reputation: 5818

Append items from list A to list B, if they are not already in list B

So say I have the following lists:

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

I would like to append the unique items from each list as they are looped over into a new array to end up with:

unique_list = [1,2,3,5,4]

I still don't full comprehend list comprehension for more advanced cases, however I'm thinking the following clearly incorrect code would convey my intentions:

def append_unique(new_list):
    unique_list.append(item) for item in new_list if item not in unique_list
unique_list = []    

append_unique([1,2,3])
append_unique([5,2,3])
append_unique([5,4,2])

Is this even possible with a one-liner, or should I concede and go for a nested solution?

UPDATE

Sorry I don't think I've conveyed this particularly well, I need to add each additional list's unique items as part of a loop, hence why each needs to individually pass through append_unique()

I attempted to modify append_unique() to use set() as per the following:

def append_unique(new_list):
    unique_list = list(set(unique_list + new_list))
unique_list = []    

append_unique([1,2,3])
append_unique([5,2,3])
append_unique([5,4,2])

The problem here of course is that I get the error, which I don't fully understand how to get around:

local variable 'unique_list' referenced before assignment

Upvotes: 2

Views: 629

Answers (2)

TerryA
TerryA

Reputation: 59974

If order does not matter, you can use sets:

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

If it does, then you can use itertools.groupby():

>>> from itertools import groupby
>>> res = []
>>> for ele, _ in groupby(a+b+c):
...     if ele not in res:
...             res.append(ele)
...
>>> res
[1, 2, 3, 5, 4]

Upvotes: 2

ilent2
ilent2

Reputation: 5241

If you don't mind using sets, the following code might work for you:

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

>>> my_set = set(a) | set(b) | set(c)

>>> my_set
set([1, 2, 3, 4, 5])

>>> unique_list = list(my_set)
>>> unique_list
[1, 2, 3, 4, 5]

Upvotes: 2

Related Questions