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
# Python code to combine two lists# and removing duplicates, without# removing duplicates in original list. # Initialisation of first listlist1 = [111, 222, 222, 115] # Initialisation of Second listlist2 = [222, 115, 77, 19] output = list(list1) # Using extend functionoutput.extend(y for y in list2 if y not in output) # printing resultprint(output) |
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.
# Python code to combine two lists # and removing duplicates, without # removing duplicates in original list. # Initialisation of first listlist1 = [11, 22, 22, 15] # Initialisation of Second listlist2 = [22, 15, 77, 9] # creating setunique_list1 = set(list1)unique_list2 = set(list2) # Difference in two setsdiff_element = unique_list2 - unique_list1 # union of difference + first listoutput = list1 + list(diff_element) # printing outputprint(output) |
Output:
[11, 22, 22, 15, 9, 77]
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.


