# Python - Combine two lists by maintaining duplicates in first list

PythonServer Side ProgrammingProgramming

In data analysis using python we may come across situation when two lists need to be merged. But it may be a challenge to handle the duplicate elements present in those lists. In this article we will see how to combine two lists by maintain all the elements form the first list and only the unique elements from the second list.

## Using extend

In this approach we take the first list and create a result list. Then we design a for loop to check for the presence of element of the first list in the second list and if the element is not found in the second list then it is appended to the result list using the extend function.

## Example

# Given list A
listA = ['A', 'B', 'B','X']

# Guven list B
listB= ['B', 'X', 'Z', 'P']

# Creating the result set
res = list(listA)

# Extending result with list B
res.extend(i for i in listB if i not in res)

# Get result
print(res)

Running the above code gives us the following result −

## Output

['A', 'B', 'B', 'X', 'Z', 'P']

## use set

We can apply the set function to get the unique elements present in a list. Then we find the difference in elements between these two lists to get only the unique elements form the second list. Finally we add the result of this difference to the first list.

## Example

# GIven First List
listA = ['A', 'B', 'B','X']

# Given Second list
listB= ['B', 'X', 'Z', 'P']

# makign the lists Uniq
listA_uniq = set(listA)
listB_uniq = set(listB)

# Capture unique elements from list B
diff_lists = listB_uniq - listA_uniq
res = listA + list(diff_lists)

# Get result
print(res)

Running the above code gives us the following result −

## Output

['A', 'B', 'B', 'X', 'P', 'Z']