Python Set Constructor Insights

The Python set constructor, set(), is a function that crates a Python set – a collection data structure that holds unique unordered elements. The set constructor can create a set out of various iterable data types, such as lists, tuples and strings.

Iterables are collection objects that implement a standard interface for returning their member items one by one. The set constructor, consumes those items and adds them to a set, which it then returns. Since a set holds unique elements, set() will eliminate any duplicates form the iterable it receives.

Using the Python Set Constructor

The following example demonstrates how to use the set constructor function to crate a set from a Python list.

Example:

s = set([1, 1, 2, 2, 3, 3])

print(s)

Output:

{1, 2, 3}

The example above prints the set that set() creates from the list it receives as its argument. Curly braces in Python, denote a set. The repeated values in the list are gone, as they should in a set.

Let’s see what happens when we pass set() a single string.

Example:

s = s = set('aabbcc')

print(s)

Output:

{'a', 'b', 'c'}

This output of the example above might be a bit surprising. Under the hood, set() actually doesn’t care about lists or strings, etc. It just expects an iterable object.

As stated at the beginning of the page, an iterable is a collection object capable of returning its member items one by one when asked. A Python string happens to be an iterable that returns the individual characters it’s made of one by one. As such, set() receives a string’s individual characters by using the iterable interface of the string. The resulting set is a collection of the unique individual characters that make up the string.

The Python Set Constructor Demonstrates “Duck Typing”

The design philosophy here is to treat objects in terms of what they can do rather than what they are. This is concept is often referred to as “duck typing” and is derived from the saying “if it looks like a duck, swims like a duck, and quacks like a duck, then it probably is a duck”.

Empty Sets

In Python, empty curly braces, {}, denote an empty dictionary object and cannot be used for empty sets.

The next example prints the type of empty curly braces and shows that it’s indeed a dict and not a set.

Example:

print(type({}))

Output:

<class 'dict'>

Therefore, to create an empty set, use the set constructor function without an argument – set().

Example:

print(type(set()))

Output:

<class 'set'>

Summary

  • The set constructor, set(), is a function that crates a Python set.
  • set() can create a set from any iterable type given as an argument, e.g. set([1,2,2,3,3,3]).
  • Use set() with no argument to create an empty set.