Python Set Union() Method is used to combine two sets into one. It can be used to create a new set containing the elements of both sets or to merge the two sets into one.
This article will provide a brief overview of the Python set union() method and show you how this method is useful when we want to combine two sets so that the elements in both sets are unioned together. So read on to learn more about this helpful tool.
Table of Contents
What is Set Union() Method?
Union() Method is a method in Python that allows you to combine two or more objects into one. It accepts an input of lists and returns a new list with the items from each list combined. For example, if you have two lists of strings called s1 and s2, Union() will return a list containing the string from both lists combined.
Working Of Set Union() Method

Set Union() Method Using set.union Method
The set.union() method allows you to combine two sets into a single new set. This can be useful if you are working with multiple arrays, tables, or lists and need to union all of the items in each set. For example, if you have an object called setA and an object called setB, then setA.Union(setB) will return the item representing the union of setA and setB (in this case, it would be “setC”).
setA = {1, 2, 3, 4}
setB = {4, 5, 6, 7}
print("setA U setB:", setA.union(setB))
Output

Set Union() Method Using ‘|’ Operator
The union() method combines two or more arrays, lists, or objects into a single larger array. This can be useful when you want to consolidate data from multiple sources and make it easier to work with. This method is also used to combine two or more arrays; we use the | operator for function calls.
setA = {1, 2, 3, 4}
setB = {4, 5, 6, 7}
print("setA U setB:", setA | setB)
Output

To learn more about Python Operators go through with the article, What is a Modulus(%) Operator in Python.
FAQs
What is the time complexity of set union?
The set’s runtime complexity because you need to build an empty set and insert all n elements into it, then all m elements into the freshly made set, the union() method on a collection with n items and a collection argument with m items is O(n + m).
What is the purpose of union() method in python?
A collection that contains all items from the original set and those from the specified set(s) is returned by the union() method. You may combine as many sets as you want, separated by commas. Any iterable object may be used instead of a set.
Conclusion
Union() Method is used quite often in Python, which means if all items in two or more lists are equal, including None, then the result will be a single item that contains all those values. In other words, Union() returns a new list with one item. In this article, we have discussed Python Set Union() method thoroughly and provided examples of usage. By now, you should be able to use it effectively in your Python scripts. Happy Coding.