DEV Community

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

Posted on • Edited on

Set & Frozenset functions in Python (3)

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 (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).

intersection() can return the common elements in the set or frozenset and *others (Intersection: A ∩ B) as shown below:

*Memo:

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

<Set>:

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

print(A.intersection(B))
print(A & B)
# {10, 30}

print(A.intersection(C))
print(A & C)
# {40, 30}

print(B.intersection(C))
print(B & C)
# {30}

print(A.intersection(B, C))
print(A & B & C)
# {30}

print(A.intersection())
# {40, 10, 20, 30}
Enter fullscreen mode Exit fullscreen mode

<Frozenset>:

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

print(A.intersection(B))
print(A & B)
# frozenset({10, 30})

print(A.intersection(C))
print(A & C)
# frozenset({40, 30})

print(B.intersection(C))
print(B & C)
# frozenset({30})

print(A.intersection(B, C))
print(A & B & C)
# frozenset({30})

print(A.intersection())
# frozenset({40, 10, 20, 30})
Enter fullscreen mode Exit fullscreen mode

intersection_update() can return the common elements in the set and *others (Intersection: A ∩ B) as shown below:

*Memo:

  • The 1st arguments are *others(Optional-Default:()-Type:Iterable):
    • Don't use any keywords like *others=, others=, etc.
  • intersection_update() doesn't create a copy.
  • intersection_update() doesn't exist for a frozenset.
  • &= with or without & can do intersection_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_.intersection_update(B)
A_ &= B

print(A_)
# {10, 30}

A_ = A.copy()
A_.intersection_update(C)
A_ &= C

print(A_)
# {40, 30}

B_ = B.copy()
B_.intersection_update(C)
B_ &= C

print(B_)
# {30}

A_ = A.copy()
A_.intersection_update(B, C)
A_ &= B & C

print(A_)
# {30}

A_ = A.copy()
A_.intersection_update()

print(A_)
# {40, 10, 20, 30}
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({10, 30})

A_ = A.copy()
A_ &= C

print(A_)
# frozenset({40, 30})

B_ = B.copy()
B_ &= C

print(B_)
# frozenset({30})

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

print(A_)
# frozenset({30})
Enter fullscreen mode Exit fullscreen mode

Top comments (0)