How to merge two lists with or without duplicates python with example

This tutorial explains how to concatenate two lists into a single list. Duplicates are allowed.

Python merges two lists into a list with duplicates

There are multiple ways we can do

The below approaches merge the lists into a new list, the order is insertion and iteration order, Duplicates are allowed, No sorting.

#1 using for in loop:

In this approach,

  • Create an empty list to store merged lists
  • Iterate each element from lists, and append to the merged list using the append method
  • The order is the iteration order of lists.
  • Duplicates are allowed
one = [5,2,4,41]
two = [41, 15, 61]

output =[]
for item in one:
output.append(item)
for elem in two:
output.append(item)
print(output)
[5, 2, 4, 41, 41, 41, 41]

#2 Concatenate operator:

operator is + or += used to copy two lists and appends the elements into new list Here is an example python plus operator

one = [5,2,4]
two = [41, 15, 61]

output = one + two
print(output)

Output

[5, 2, 4, 41, 15, 61]

To use +=, the variable must be defined to host the result of the merge, otherwise, throws NameError: name 'output1' is not defined with the below code.

output1 += (one+two)
print(outpu1)

The same code can be rewritten using variable declaration with empty initialization[]

# += operator
output1=[]
output1 += (one+two)
print(output1)

Output:

#3 use Unpack operator

unpack operator(*) allows you to iterate each element and copies to the list. This is introduced in Python.3.5 version.

output1 = [*one,*two]
print(output1)

Output:

[5, 2, 4, 41, 15, 61]

How to merge two lists with unique values

These examples concatenate two lists and duplicates are removed. Append the list using the + operator, and pass this result to the Set constructor. The set does not allow duplicates. Convert the set to a List using a list constructor.

Here is an example

one = [5,2,4,41]
two = [41, 15, 61]
#allow duplicates
output = one + two
print(output)

# //unique elements

output1 =list(set(one+two))
print(output1)
[5, 2, 4, 41, 41, 15, 61]
[2, 4, 5, 41, 15, 61]

How to concatenate an existing list with another list in python?

This example does not create a new list but appends elements to an end of an existing list.

The extend method is used to merge one into another

Here is an example

one = [5,2,4,41]
two = [41, 15, 61]
one.extend(two)
print(one)

Output

[5, 2, 4, 41, 41, 15, 61]