The set constructor

Recall that somewhat confusingly, empty curly braces create an empty dictionary, rather than an empty set:

>>> d = {}
>>> type(d)
<class 'dict'>

To create an empty set we must resort to the set() constructor:

>>> e = set()
>>> e
set()

This is also the form Python echoes back to us for empty sets.

The set() constructor can create a set from any iterable series, such as a list:

>>> s = set([2, 4, 16, 64, 4096, 65536, 262144])
>>> s
{64, 4096, 2, 4, 65536, 16, 262144}

Duplicates in the input series are discarded. In fact, a common use of sets is to efficiently remove duplicate items from series of objects:

>>> t = [1, 4, 2, 1, 7, 9, 9]
>>> set(t)
{1, 2, 4, 9, 7}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset