DEV Community

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

Posted on • Edited on

Set & Frozenset functions in Python (5)

Buy Me a Coffee

*Memo:

  • My post explains set and frozenset functions (1).
  • My post explains set and frozenset functions (2).
  • My post explains set and frozenset functions (3).
  • My post explains set and frozenset functions (4).
  • 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).

symmetric_difference() can return the elements in either the set (or frozenset) or other but not both with (Symmetric Difference: A Δ B) as shown below:

*Memo:

  • The 1st argument is other(Required-Type:Iterable):
    • Don't use other=.
  • symmetric_difference() creates a copy.
  • ^ can do symmetric_difference(), creating a copy and supporting set and frozenset.

<Set>:

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

print(A.symmetric_difference(B))
print(A ^ B)
# {40, 50, 20}

print(A.symmetric_difference(C))
print(A ^ C)
# {10, 20}

print(B.symmetric_difference(C))
print(B ^ C)
# {40, 10, 50}
Enter fullscreen mode Exit fullscreen mode

<Frozenset>:

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

print(A.symmetric_difference(B))
print(A ^ B)
# frozenset({40, 50, 20})

print(A.symmetric_difference(C))
print(A ^ C)
# frozenset({10, 20})

print(B.symmetric_difference(C))
print(B ^ C)
# frozenset({40, 10, 50})
Enter fullscreen mode Exit fullscreen mode

symmetric_difference_update() can return the elements in either the set or other but not both with (Symmetric Difference: A Δ B) as shown below:

*Memo:

  • The 1st argument is other(Required-Type:Iterable):
    • Don't use other=.
  • symmetric_difference_update() doesn't create a copy.
  • symmetric_difference_update() doesn't exist for a frozenset.
  • ^= can do symmetric_difference_update(), creating a copy and supporting set and frozenset.

<Set>:

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

A_ = A.copy()
A_.symmetric_difference_update(B)
# A_ ^= B

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

A_ = A.copy()
A_.symmetric_difference_update(C)
# A_ ^= C

print(A_)
# {10, 20}

B_ = B.copy()
B_.symmetric_difference_update(C)
# B_ ^= C

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

<Frozenset>:

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

A_ = A.copy()
A_ ^= B

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

A_ = A.copy()
A_ ^= C

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

B_ = B.copy()
B_ ^= C

print(B_)
# frozenset({40, 10, 50})
Enter fullscreen mode Exit fullscreen mode

Top comments (0)