Combining two lists and removing duplicates, without removing duplicates in original list
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Isolated
--
Chapters
00:00 Question
01:09 Accepted answer (Score 230)
01:44 Answer 2 (Score 122)
01:55 Answer 3 (Score 70)
02:10 Answer 4 (Score 26)
02:21 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
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Isolated
--
Chapters
00:00 Question
01:09 Accepted answer (Score 230)
01:44 Answer 2 (Score 122)
01:55 Answer 3 (Score 70)
02:10 Answer 4 (Score 26)
02:21 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 ) )