Free cookie consent management tool by TermsFeed Python Set - union method | Pythontic.com

Python Set - union method

Method signature:

union(anotherSet_in)

Method overview: 

  • Produces a new set containing the union of elements from two sets.
  • While the new set is created afresh its elements are shallow copies from set1 and set2 involved in the union operation.

Parameters:

anotherSet_in: The second set of the union operation.

Example:

# Example Python program that takes the union of two sets

# Create sets of great lakes based on a criterion
onlyInUS         = {"Lake Michigan"}
inUSAndCanada    = {"Lake Superior", "Lake Huron", "Lake Erie", "Lake Ontario"}

# Take a union of great lakes
greatLakes        = onlyInUS.union(inUSAndCanada)
print(greatLakes)
print(id(onlyInUS))
print(id(inUSAndCanada))

Output:

{'Lake Michigan', 'Lake Superior', 'Lake Erie', 'Lake Ontario', 'Lake Huron'}

4377792736

4377791392

4377793856

 


Copyright 2025 © pythontic.com