DEV Community

Super Kai (Kazuya Ito)
Super Kai (Kazuya Ito)

Posted on • Edited on

Set & Frozenset functions in Python (2)

Buy Me a Coffee

*Memo:

  • My post explains set and frozenset functions (1).
  • My post explains set and frozenset functions (3).
  • My post explains set and frozenset functions (4).
  • My post explains set and frozenset functions (5).
  • My post explains set and frozenset functions (6).
  • My post explains set and frozenset functions (7).
  • My post explains a set (1).
  • My post explains a frozenset (1).

union() can return all the elements in the set or frozenset and *others (Union: A ∪ B) as shown below:

*Memo:

  • The 1st arguments are *others(Optional-Default:()-Type:Iterable):
    • Don't use any keywords like *others=, others=, etc.
  • union() creates a copy.
  • | can do union(), creating a copy and supporting set and frozenset.

<Set>:

A = {10, 50}
B = {10, 30, 50}
C = {10, 20, 40, 50}

print(A.union(B))
print(A | B)
# {50, 10, 30}

print(A.union(C))
print(A | C)
# {50, 20, 40, 10}

print(B.union(C))
print(B | C)
# {50, 20, 40, 10, 30}

print(A.union(B, C))
print(A | B | C)
# {50, 20, 40, 10, 30}

print(A.union())
# {10, 50}
Enter fullscreen mode Exit fullscreen mode

<Frozenset>:

A = frozenset([10, 50])
B = frozenset([10, 30, 50])
C = frozenset([10, 20, 40, 50])

print(A.union(B))
print(A | B)
# frozenset({50, 10, 30})

print(A.union(C))
print(A | C)
# frozenset({50, 20, 40, 10})

print(B.union(C))
print(B | C)
# frozenset({50, 20, 40, 10, 30})

print(A.union(B, C))
print(A | B | C)
# frozenset({50, 20, 40, 10, 30})

print(A.union())
# frozenset({10, 50})
Enter fullscreen mode Exit fullscreen mode

update() can return all the elements in the set and *others (Union: A ∪ B) as shown below:

*Memo:

  • The 1st arguments are *others(Optional-Default:()-Type:Iterable):
    • Don't use any keywords like *others=, others=, etc.
  • update() doesn't create a copy.
  • update() doesn't exist for a frozenset.
  • |= with or without | can do update(), creating a copy and supporting set and frozenset.

<Set>:

A = {10, 50}
B = {10, 30, 50}
C = {10, 20, 40, 50}

A_ = A.copy()
A_.update(B)
A_ |= B

print(A_)
# {50, 10, 30}

A_ = A.copy()
A_.update(C)
A_ |= C

print(A_)
# {50, 20, 40, 10}

B_ = B.copy()
B_.update(C)
B_ |= C

print(B_)
# {40, 10, 50, 20, 30}

A_ = A.copy()
A_.update(B, C)
A_ |= B | C

print(A_)
# {40, 10, 50, 20, 30}

A_ = A.copy()
A_.update()

print(A_)
# {10, 50}
Enter fullscreen mode Exit fullscreen mode

<Frozenset>:

A = frozenset([10, 50])
B = frozenset([10, 30, 50])
C = frozenset([10, 20, 40, 50])

A_ = A.copy()
A_ |= B

print(A_)
# frozenset({50, 10, 30})

A_ = A.copy()
A_ |= C

print(A_)
# frozenset({50, 20, 40, 10})

B_ = B.copy()
B_ |= C

print(B_)
# frozenset({50, 20, 40, 10, 30})

A_ = A.copy()
A_ |= B | C

print(A_)
# frozenset({50, 20, 40, 10, 30})
Enter fullscreen mode Exit fullscreen mode

Top comments (0)