Set

A set in Python is a collection of unique and immutable (unchangeable) objects.

# start with an empty set

my_set = set()

print(my_set)
set()
# add a few elements

my_set.add('a')
my_set.add('b')
my_set.add('c')
my_set.add(1)
my_set.add(2)
my_set.add(3)

print(my_set)
{1, 2, 3, 'b', 'c', 'a'}
for element in my_set:
    print(element)
1
2
3
b
c
a
# and they haven't changed. What if we remove "a"
my_set.remove("a")
print("there are", len(my_set), "elements in my_set")
print(my_set)
there are 5 elements in my_set
{1, 2, 3, 'b', 'c'}
# Initializing two sets

odds   = set([1,3,5,7,9])
primes = set([2,3,5,7])

# Demonstration of the "intersection" between two sets
# The intersection corresponds to the overlapping region
# in the Venn Diagram above.

odd_AND_prime = odds.intersection(primes)
print(odd_AND_prime)

{3, 5, 7}

# Demonstration of the "union" of two sets. The union
# of sets A and B includes ANY element that is in A OR B 
# or both.

odd_OR_prime = odds.union(primes)
print(odd_OR_prime)

{1, 2, 3, 5, 7, 9}

# Demonstration of the "set difference" between two sets.
# What do you expect odds-primes to return?

odd_not_prime = odds - primes
print(odd_not_prime)

{1, 9}

# Another demo of "set difference"

prime_not_odd = primes - odds
print(prime_not_odd)

{2}

Last updated