Python Set - union method

The union method of Python set class creates a new set object containing the elements from both set1 and set2 involved in the union operation.

Set Updated 15 Sep 2016 1 min read

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

python
# 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

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

4377792736

4377791392

4377793856