What is the purpose of the set() function?

It is a constructor that takes a data object, extracts unique values and returns a set object…

set([1,1,2,2,3,4,4,5,6,6])    # {3, 2, 6, 4, 1, 5}

Sets are iterable, but not mutable and they have no order.

1 Like

We can actually modify the value of a set. Another related type, a frozenset, cannot be modified. As a consequence, while a set cannot serve as a key in a dict, a frozenset can do so. See below:

>>> a = set([1,1,2,2,3,4,4,5,6,6])
>>> a
{1, 2, 3, 4, 5, 6}
>>> a.add(7)
>>> a
{1, 2, 3, 4, 5, 6, 7}
>>> b = {}
>>> type(b)
<class 'dict'>
>>> b[a] = 8
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    b[a] = 8
TypeError: unhashable type: 'set'
>>> c = frozenset(a)
>>> b[c] = 8
>>> b[c]

So basically if you have a list with a bunch of duplicates. set() will return a single value for each one?

1 Like

That’s correct. There can be no duplicates in a set. A close comparison is a dictionary in which there can be no duplicate keys.

Sets in Python

A Set is an unordered collection data type that is iterable, mutable, and has no duplicate elements. Python’s set class represents the mathematical notion of a set. The major advantage of using a set, as opposed to a list, is that it has a highly optimized method for checking whether a specific element is contained in the set. This is based on a data structure known as a hash table.

Frozen Sets Frozen sets are immutable objects that only support methods and operators that produce a result without a?ecting the frozen set or sets to which they are applied.