DEV Community

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

Posted on • Edited on

Set in Python (1)

Buy Me a Coffee

*Memo:

A set:

  • is the unordered mutable(unhashable) collection of zero or more elements whose type is set:
    • Unordered means that the order of each element in a set isn't kept so it doesn't guarantee that the order is always the same.
    • Mutable(Unhashable) means the elements of a set can be changed:
  • doesn't allow duplicated elements (even with different types).
  • can have the hashable types of elements:
    • A hashable type is the type whose value cannot be changed like str, bytes, int, float, complex, bool, tuple, frozenset, range or iterator.
  • cannot have the unhashable types of elements:
    • A unhashable type is the type whose value can be changed like bytearray, list, set or dict.
  • can be used with len() to get the length.
  • is True if it's non-empty and False if it's empty, checking it with bool().
  • is False if it's non-empty and True if it's empty, inverting the truth value with not keyword.
  • can be checked if a specific element is and isn't in the set with in keyword and with not and in keyword respectively.
  • can be checked if the set is and isn't referred to by two variables with is keyword and with is and not keyword respectively:
    • Set literals with is keyword and with is and not keyword don't get warnings respectively.
  • and other set can be checked if all the elements in:
    • them are and aren't the same with == and != respectively.
    • the set are in other set with <=.
    • other set are in the set with >=.
    • the set and other elements are in other set with <.
    • other set and other elements are in the set with >.
  • and other set can be checked if they have and don't have their common elements with bool() and & and with not keyword and & respectively.
  • cannot be enlarged with * and a number.
  • and other sets cannot be concatenated with +.
  • and other set can return:
    • all the elements in them with '|' (Union: A ∪ B).
    • their common elements with '&' (Intersection: A ∩ B).
    • the elements in the set which aren't in other set with '-' (Difference: A - B).
    • the elements in either the set or other set but not both with '^' (Symmetric Difference: A Δ B).
  • can be iterated with a for statement.
  • can be unpacked with an assignment and for statement, function and * but not with **.
  • can be created by {} with or without ',', by set() with or without an iterable and by a set comprehension:
    • For set(), the words type conversion are also suitable in addition to the word creation.
  • cannot be big because it gets MemoryError.
  • cannot be read by indexing and slicing.
  • cannot be changed by indexing, slicing and a del statement.
  • can be continuously used through multiple variables.
  • with a frozenset can be shallow-copied by set.copy(), copy.copy() and set().
  • with a frozenset can be deep-copied by copy.deepcopy().

Be careful, a big set gets MemoryError.


{} with or without ',' can create a set as shown below:

*Memo:

  • Be careful, the empty curlybraces {} are an empty dictionary but not an empty set so use set() to create an empty set.
A = set()                                                   # Empty 1D set
A = {}                                                      # dict not set
A = {10, 20, 30, 40, 50}                                    # 1D set
A = {10, 20, 30, 10, 20, 30}                                # 1D set
A = {10, 20, 30, 40, frozenset({50, 60, 70, 80})}           # 2D set
A = {frozenset({10, 20, 30, 40}),                           # 2D set
     frozenset({50, 60, 70, 80})}
A = {frozenset({10, 20, 30, 40}),                           # 3D set
     frozenset({frozenset({50, 60}), frozenset({70, 80})})}
A = {frozenset({frozenset({10, 20}), frozenset({30, 40})}), # 3D set
     frozenset({frozenset({50, 60}), frozenset({70, 80})})}
# No error

print({0, 0.0, 0.0+0.0j, False})
print({1, 1.0, 1.0+0.0j, True})
print({'A', b'A', 2, 2.3, 2.3+4.5j, True, (2, 3),
      frozenset({2, 3}), range(2, 3), iter([2, 3])})
print(len({10, 20, 30, 40, 50}))
print(bool({0}))
print(bool({frozenset()}))
print(bool(set()))
print(not {0})
print(not {frozenset()})
print(not set())
print(10 in {10, frozenset([20, 30])})
print(10 not in {10, frozenset([20, 30])})
print({10, 20, 30} is {10, 20, 30})     # No warning
print({10, 20, 30} is not {10, 20, 30}) # No warning
print({10, 20, 30} == {10, 20, 30})
print({10, 20, 30} != {10, 20, 30})
print({10, 20, 30} <= {10, 20, 30})
print({10, 20, 30} >= {10, 20, 30})
print({10, 20, 30} < {10, 20, 30})
print({10, 20, 30} > {10, 20, 30})
print(bool({10, 20, 30} & {20, 40}))
print(not ({10, 20, 30} & {20, 40}))
print({10, 50} | {10, 30, 50})
print({10, 20, 30, 40} & {10, 30, 50})
print({10, 20, 30, 40} - {10, 30, 50})
print({10, 20, 30, 40} ^ {10, 30, 50})
for x in {0, 1, 2, 3, 4}: print(x)
for x in {frozenset({10, 20, 30, 40}),
          frozenset({50, 60, 70, 80})}: print(x)
for x in {frozenset({frozenset({10, 20}), frozenset({30, 40})}),
          frozenset({frozenset({50, 60}), frozenset({70, 80})})}: print(x)
v1, v2, v3 = {0, 1, 2}; print(v1, v2, v3)
v1, *v2, v3 = {0, 1, 2, 3, 4, 5}; print(v1, v2, v3)
for v1, v2, v3 in {frozenset({0, 1, 2}),
                   frozenset({3, 4, 5})}: print(v1, v2, v3)
for v1, *v2, v3 in {frozenset({0, 1, 2, 3, 4, 5}),
                    frozenset({6, 7, 8, 9, 10, 11})}: print(v1, v2, v3)
print(*{0, 1}, 2, *{3, 4, *{5}})
print({*{0, 1}, 2, *{3, 4, *{5}}})
print({x**2 for x in {0, 1, 2, 3, 4, 5, 6, 7}})
print({frozenset(y**2 for y in x) for x in {frozenset({0, 1, 2, 3}),
                                            frozenset({4, 5, 6, 7})}})
print({frozenset(frozenset(z**2 for z in y) for y in x) for x in
          {frozenset({frozenset({0, 1}), frozenset({2, 3})}),
           frozenset({frozenset({4, 5}), frozenset({6, 7})})}}
# No error

print({10, 20, [30, 40], 50, 60})
print({10, 20, {30, 40}, 50, 60})
print({10, 20, {30:40, 50:60}, 70, 80})
print({bytearray(b'Hello')})
print({10, 20, 30, 40, 50} * 3)
print({10, 20, 30} + {30, 40} + {50, 60, 70, 80})
print(set(range(1000000000)))
print({x for x in range(1000000000)})
# Error
Enter fullscreen mode Exit fullscreen mode

A set is the unordered mutable(unhashable) collection of zero or more elements whose type is set as shown below:

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

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

print(type(A))
# <class 'set'>

A.remove(20)
A.remove(40)

print(A)
# {50, 10, 30}
Enter fullscreen mode Exit fullscreen mode
A = set() # Empty set

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

A set doesn't allow duplicated elements (even with different types) as shown below:

A = {10, 20, 30, 10, 20, 30}

print(A)
# {10, 20, 30}
Enter fullscreen mode Exit fullscreen mode
A = {0, 0.0, 0.0+0.0j, False}

print(A)
# {0}
Enter fullscreen mode Exit fullscreen mode
A = {1, 1.0, 1.0+0.0j, True}

print(A)
# {1}
Enter fullscreen mode Exit fullscreen mode

A set can have the hashable types of elements as shown below:

A = {'A', b'A', 2, 2.3, 2.3+4.5j, True, (2, 3),
     frozenset({2, 3}), range(2, 3), iter([2, 3])}
print(A)
# {True, 2, 2.3, frozenset({2, 3}),
#  <list_iterator object at 0x000001F3B9E5F250>,
#  b'A', (2.3+4.5j), (2, 3), 'A', range(2, 3)}
Enter fullscreen mode Exit fullscreen mode

A set cannot have the unhashable types of elements as shown below:

A = {10, 20, [30, 40], 50, 60}       # set(list)
# TypeError: unhashable type: 'list'

A = {10, 20, {30, 40}, 50, 60}       # set(set)
# TypeError: unhashable type: 'set'

A = {10, 20, {30:40, 50:60}, 70, 80} # set(dict)
# TypeError: unhashable type: 'dict'

A = {bytearray(b'Hello')}            # set(bytearray)
# TypeError: unhashable type: 'bytearray'
Enter fullscreen mode Exit fullscreen mode

A set can be used with len() to get the length as shown below:

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

print(len(A))
# 5
Enter fullscreen mode Exit fullscreen mode

Top comments (0)