A set is an unordered collection with no duplicate elements. Sets are used for membership testing, removing duplicate entries and performing set operations such as intersection, union and difference.

There are two built-in set types: set and frozenset. The set type is mutable and the frozenset type is immutable.

Set construction:

  • set() for empty set. Note: {} cannot be used
  • set(values)
  • {value1,valuen}

Construction of frozenset is very similar and uses frozenset() instead of set().

Set examples:

myset1=set()
print(myset1)
set()

myset2=set('aaabbcc')
print(myset2)
{'b', 'a', 'c'}

myset3={'python','java','c#','php'}
print(myset3)
{'c#', 'php', 'java', 'python'}

Operators that can be used on sets and frozensets with example:

#membership testing
print('python' in myset3)
True

#find length
print(len(myset3))
4

myset4={'python','c++'}

#intersection
print(myset3.intersection(myset4))
{'python'}

#difference
print(myset3.difference(myset4))
{'c#', 'php', 'java'}

#union
print(myset3.union(myset4))
{'php', 'python', 'c#', 'java', 'c++'}

#add element to set
myset4.add('lisp')
print(myset4)
{'c++', 'python', 'lisp'}

#remove lement from set
myset4.remove('c++')
print(myset4)
{'python', 'lisp'}

#equality testing
print(myset3==myset4)
False

Operations that involve modification of set data such as add() and remove() cannot be used on frozensets.

Code for today’s plog is here.

References: