Skip to content

Python union list of sets | Example code

  • by

Union of the list using sets will Lists without repetition of common elements in Python. The Union of two lists means it will contain all the elements of both lists.

Example union list of sets in Python

Simple example code union of two lists using set.

l1 = [1, 2, 3, 4, 5]
l2 = [2, 4, 6, 8, 10]

res = list(set(l1 + l2))

print(res)

Output:

Python union list of sets

OR

Using the Union method.

l1 = [1, 2, 3, 4, 5]
l2 = [2, 4, 6, 8, 10]

res = list(set(l1).union(set(l2)))

print(res)

Note: the order of elements in the resulting set may not be the same as the original order of elements in the sets list, as sets are unordered collections in Python.

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

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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading