Skip to content

Union of two lists Python | Example code

  • by

Use plus “+” operator to Union of two lists in Python. Union of two lists means combining two lists into one, all the elements from list A and list B, and putting them inside a single new list.

Example union of two lists Python

Simple example code with Union list reflecting the repetition.

lst1 = [1, 2, 3, 4]
lst2 = [5, 6, 1]

new_list = lst1 + lst2

print(new_list)

Output:

Union of two lists Python

Or you can use the union operator (|) or the set() function. Here’s an example of how you can do it:

list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]

# Using the union operator
union_list = list(set(list1) | set(list2))
print(union_list)

# Using the set() function
union_list = list(set(list1).union(list2))
print(union_list)

In both cases, the set() function is used to convert each list into a set, which automatically eliminates any duplicate elements. Then, the union of the two sets is taken using either the union operator (|) or the union() method. Finally, the resulting set is converted back to a list using the list() function.

Without Repetition

we use the set() function on both lists, individually and then use the union function or union operator.

lst1 = [1, 2, 3, 4]
lst2 = [5, 6, 1]

# final_list = list(set(lst1) | set(lst2))
new_list = list(set(lst1).union(set(lst2)))

print(new_list)

Output: [1, 2, 3, 4, 5, 6]

Do comment if you have any doubts or suggestions on this Python list.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *