A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python/union-function-python/ below:

Union() function in Python - GeeksforGeeks

Union() function in Python

Last Updated : 22 Feb, 2025

Union() method in Python is an inbuilt function provided by the set data type. It is used to combine multiple sets into a single set, containing all unique elements from the given sets. It ensures that no duplicate values exist in the final set.

Python Set Union

The symbol for denoting union of sets is 'U'.

Example:

Python
A = {1, 2, 3} 
B = {3, 4, 5}

print(A.union(B))  # Combining both sets
Union() Syntax

set1.union(set2, set3, ...)

Parameters:

Returns:

Union() examples

Let us see a few examples of the set union() function in Python.

Using Union() on multiples sets

We can merge three or more sets at once .

Python
A = {2, 4, 5, 6}
B = {4, 6, 7, 8}
C = {7, 8, 9, 10}

# using multiple union calls
print("A U B U C:", A.union(B).union(C))

# directly passing multiple sets
print("A U B U C:", A.union(B, C))

Output
A U B U C: {2, 4, 5, 6, 7, 8, 9, 10}
A U B U C: {2, 4, 5, 6, 7, 8, 9, 10}

Explanation:

Using | Operator

we can use the | (pipe operator) as a shortcut for performing a union operation on sets.

Python
A = {2, 4, 5, 6}
B = {4, 6, 7, 8}
C = {7, 8, 9, 10}

# Using | operator for union
print("A U B:", A | B)
print("A U B U C:", A | B | C)

Output
A U B: {2, 4, 5, 6, 7, 8}
A U B U C: {2, 4, 5, 6, 7, 8, 9, 10}

Explanation:

Using Union() with Strings

union() method works on sets of strings as well.

Python
A = {'ab', 'ba', 'cd', 'dz'} 
B = {'cd', 'ab', 'dd', 'za'}

print("A U B:", A.union(B))

Output
A U B: {'dd', 'dz', 'ab', 'ba', 'cd', 'za'}

Explanation:



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4