Sets

We'll cover the following...

A set is an unordered “bag” of unique values. A single set can contain values of any immutable datatype. Once you have two sets, you can do standard set operations like union, intersection, and set difference.

Creating A Set

First things first. Creating a set is easy.

Press + to interact
a_set = {1} #①
print (a_set)
#{1}
print (type(a_set)) #②
#<class 'set'>
a_set = {1, 2} #③
print (a_set)
#{1, 2}

① To create a set with one value, put the value in curly brackets ({}).

② Sets are actually implemented as classes, but don’t worry about that for now.

③ To create a set with multiple values, separate the values with commas and wrap it all up with curly brackets.

You can also create a set out of a list.

Press + to interact
a_list = ['a', 'b', 'mpilgrim', True, False, 42]
a_set = set(a_list) #①
print (a_set ) #②
#{False, True, 'mpilgrim', 'b', 42, 'a'}
print (a_list ) #③
#['a', 'b', 'mpilgrim', True, False, 42]

① To create a set from a list, use the set() function. (Pedants who know about how sets are implemented will point out that this is not really calling a function, but instantiating a class. I promise you will learn the difference later in this book. For now, just know that set() acts like a function, and it returns a set.)

② As I mentioned earlier, a single set can contain values of any datatype. And, as I mentioned earlier, sets are unordered. This set does not remember the original order of the list that was used to create it. If you were to add items to this set, it would not remember ...

Access this course and 1400+ top-rated courses and projects.