Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining two lists and removing duplicates, without removing duplicates in original list

Tags:

python

list

People also ask

How do I combine two lists without duplicates?

You can also merge lists without duplicates in Google Sheets. Select and right-click a second range that will be merged (e.g., C2:C6) and click Copy (or use the keyboard shortcut CTRL + C).

How do you merge two lists without duplicates in python?

Python merges two lists without duplicates could be accomplished by using a set. And use the + operator to merge it.


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)))

resulting_list = list(first_list)
resulting_list.extend(x for x in second_list if x not in resulting_list)

You can use sets:

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

resultList= list(set(first_list) | set(second_list))

print(resultList)
# Results in : resultList = [1,2,5,7,9]

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

print( set( first_list + second_list ) )