6. Set

Type of data - same as in mathematics

6.1. Defining

>>> A = {1, 2, 3, 4, 5}
>>> B = {4, 5, 6, 7, 8}

6.2. Checking type

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

6.3. Operation on sets

  • Checking set length

>>> len(A)
5
  • Checking element occurrence

>>> 17 in A
False
>>> 3 in A
True
  • Adding element to the set

>>> A.add(17)
>>> 17 in A
True
  • Union

C = A | B
print(C)
{1, 2, 3, 4, 5, 6, 7, 8, 17}
>>> print(C.issuperset(A))
True
>>> print(C.issuperset(A))
True
  • Intersection - Common set

>>> D = A & B
>>> print(D)
{4, 5}
  • Difference

E = A - B
print(E)
{1, 2, 3, 17}
F = B - A
print(F)
{8, 6, 7}
  • Symmetric difference

>>> print(A.symmetric_difference(B))
{1, 2, 3, 17, 6, 7, 8}

6.4. Immutable sets

>>> A = frozenset([1, 2, 3, 4])

6.5. Implementation

Code written in C to review.

6.6. Exercises - part 1

  • having sets:

    • A = {‘wp.pl’, ‘onet.pl’, ‘google.com’, ‘ing.pl’, ‘facebook.com’}

    • B = {‘wp.pl’, ‘youtube.pl’, ‘wikipedia.org’, ‘ovh.com’, ‘facebook.com’}

  • Find:

    • Instersection of domains

    • Domains existing in just one of the sets

6.7. Exercises - part 2

  • Having list [1, 2, 4, 5, 7, 7, 7] print only unique values