Python | Combine two lists by maintaining duplicates in first list

Given two lists, the task is to combine two lists and removing duplicates, without removing duplicates in original list.

Example:

Input : 
list_1 = [11, 22, 22, 15]
list_2 = [22, 15, 77, 9]

Output :
OutList = [11, 22, 22, 15, 77, 9]

Code #1: using extend

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to combine two lists
# and removing duplicates, without
# removing duplicates in original list.
  
# Initialisation of first list
list1 = [111, 222, 222, 115]
  
# Initialisation of Second list
list2 = [222, 115, 77, 19]
  
output = list(list1)
  
# Using extend function
output.extend(y for y in list2 if y not in output)
  
# printing result
print(output)

chevron_right


Output:

[111, 222, 222, 115, 77, 19]

 
Code #2 : Using Set and Iteration
Append those element in first list which are not in second list and then take union of first and second list.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to combine two lists 
# and removing duplicates, without 
# removing duplicates in original list.
  
# Initialisation of first list
list1 = [11, 22, 22, 15]
  
# Initialisation of Second list
list2 = [22, 15, 77, 9]
  
# creating set
unique_list1 = set(list1)
unique_list2 = set(list2)
  
# Difference in two sets
diff_element = unique_list2 - unique_list1
  
# union of difference + first list
output = list1 + list(diff_element)
  
# printing output
print(output) 

chevron_right


Output:

[11, 22, 22, 15, 9, 77]


My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.