tags:

views:

660

answers:

3

I have two lists that i need to combine where the second list has any duplicates of the first list ignored. .. A bit hard to explain, so let me show an example of what the code looks like, and what i want as a result.

first_list = [1, 2, 2, 5]

second_list = [2, 5, 7, 9]

# The result of combining the two lists should result in this list:
resulting_list = [1, 2, 2, 5, 7, 9]

You'll notice that the result has the first list, including its two "2" values, but the fact that second_list also has an additional 2 and 5 value is not added to the first list.

Normally for something like this i would use sets, but a set on first_list would purge the duplicate values it already has. So i'm simply wondering what the best/fastest way to achieve this desired combination.

Thanks.

+7  A: 

You need to append to the first list those elements of the second list that aren't in the first - sets are the easiest way of determining which elements they are, like this:

first_list = [1, 2, 2, 5]
second_list = [2, 5, 7, 9]

in_first = set(first_list)
in_second = set(second_list)

in_second_but_not_in_first = in_second - in_first

result = first_list + list(in_second_but_not_in_first)
print result  # Prints [1, 2, 2, 5, 9, 7]

Or if you prefer one-liners 8-)

print first_list + list(set(second_list) - set(first_list))
RichieHindle
Or this if you need it sorted: print first_list + sorted(set(second_list) - set(first_list))
hughdbrown
+1  A: 
resulting_list = first_list + [i for i in second_list if i not in first_list]
Daniel Roseman
setify first_list and you're "set"
kaizer.se
The resulting list won't be sorted.
avakar
It's an O(m*n) algorithm.
hughdbrown
+1  A: 
resulting_list = list(first_list)
resulting_list.extend(x for x in second_list if x not in resulting_list)
Ned Batchelder
Good point! fixed.
Ned Batchelder
Also an O(m*n) algorithm.
hughdbrown