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