Set Basics

January 12, 2018

Set Basics

Sets in Python can be used to store an unordered, unique collection. True to its name, it also supports the mathematical operations of union, intersect, difference and symmetric difference.


Creating a Set

Sets can be created by putting the items in curly braces, or by using the set() function. Do note that empty curly braces does not create a set - that creates a dictionary.

unique_fruits = {'apple', 'apple', 'banana', 'banana', 'coconut', 'coconut'}
print(unique_fruits)
{'coconut', 'banana', 'apple'}
unique_fruits = set(['apple', 'apple', 'banana', 'banana', 'coconut', 'coconut'])
print(unique_fruits)
{'coconut', 'banana', 'apple'}


Set Operations

set_one = set(['apple', 'banana', 'coconut', 'durian'])
set_two = set(['apple', 'banana', 'coconut'])


Union returns the unique members when we combine both sets.

print(set_one | set_two)
{'durian', 'coconut', 'banana', 'apple'}


Intersect returns the set of items that are in both sets.

print(set_one & set_two)
{'coconut', 'banana', 'apple'}


Difference returns the set of items that are in the first set, but not in the second set.

print(set_one - set_two)
{'durian'}
print(set_two - set_one)
set()


Symmetric difference returns the set of items in the first set or the second set, but not both.

print(set_one ^ set_two)
{'durian'}
comments powered by Disqus