DEV Community

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

Posted on • Edited on

Set & Frozenset functions in Python (1)

Buy Me a Coffee

*Memo:

  • 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 a set (1).
  • My post explains a frozenset (1).

add() can add a value to the set as shown below:

*Memo:

  • The 1st argument is elem(Required-Type:Any):
    • Don't use elem=.
  • add() doesn't create a new set.
  • add() doesn't exist for a frozenset.

<Set>:

A = {10, 30, 50}

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

A.add(20)
print(A)
# {10, 50, 20, 30}

A.add(30)
print(A)
# {10, 50, 20, 30}

A.add(40)
print(A)
# {40, 10, 50, 20, 30}

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

remove() can remove the element matched to elem from the set, getting error if the element doesn't exist in the set as shown below:

*Memo:

  • The 1st argument is elem(Required-Type:Any):
    • Don't use elem=.
  • remove() doesn't create a new set.
  • remove() doesn't exist for a frozenset.

<Set>:

A = {10, 30, 50, 70}

print(A)
# {10, 50, 70, 30}

A.remove(50)
print(A)
# {10, 70, 30}

A.remove(70)
print(A)
# {10, 30}

A.remove(20)
# KeyError: 20
Enter fullscreen mode Exit fullscreen mode

discard() can remove the element matched to elem from the set, not getting error even if the element doesn't exist in the set as shown below:

*Memo:

  • The 1st argument is elem(Required-Type:Any):
    • Don't use elem=.
  • discard() doesn't create a new set.
  • discard() doesn't exist for a frozenset.

<Set>:

A = {10, 30, 50, 70}

print(A)
# {10, 50, 70, 30}

A.discard(50)
print(A)
# {10, 70, 30}

A.discard(70)
print(A)
# {10, 30}

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

pop() can remove and throw an arbitrary element from the set as shown below:

*Memo:

  • It has no arguments.
  • Error occurs if the set is empty.
  • pop() doesn't create a new set.
  • pop() doesn't exist for a frozenset.

<Set>:

A = {10, 30, 50}

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

print(A.pop()) # 10
print(A)       # {50, 30}

print(A.pop()) # 50
print(A)       # {30}

print(A.pop()) # 30
print(A)       # set()

print(A.pop())
# KeyError: 'pop from an empty set'
Enter fullscreen mode Exit fullscreen mode

clear() can remove all elements from the set as shown below:

*Memo:

  • It has no arguments.
  • clear() doesn't create a new set.
  • clear() doesn't exist for a frozenset.

<Set>:

A = {10, 30, 50}

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

A.clear()
print(A)
# set()
Enter fullscreen mode Exit fullscreen mode

Top comments (0)