The Python Oracle

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

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Lost Civilization

--

Chapters
00:00 Combining Two Lists And Removing Duplicates, Without Removing Duplicates In Original List
00:49 Accepted Answer Score 240
01:14 Answer 2 Score 136
01:21 Answer 3 Score 79
01:31 Answer 4 Score 30
01:36 Thank you

--

Full question
https://stackoverflow.com/questions/1319...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #list

#avk47



ACCEPTED ANSWER

Score 240


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



ANSWER 2

Score 136


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



ANSWER 3

Score 79


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]



ANSWER 4

Score 30


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

print( set( first_list + second_list ) )