Learn about Python Sets (lists)

Learn about Python Sets (lists) Sets are lists with no duplicate entries. Let’s say you want to collect a list of words used in a paragraph:

print(set("my name is Eric and Eric is my name".split()))

Trinket.io on-line Python compiler

This will print out a list containing “my”, “name”, “is”, “Eric”, and finally “and”. Since the rest of the sentence uses words which are already in the set, they are not inserted twice.

Sets are a powerful tool in Python since they have the ability to calculate differences and intersections between other sets. For example, say you have a list of participants in events A and B:

a = set(["Jake", "John", "Eric"])
print(a)
b = set(["John", "Jill"])
print(b)

Trinket.io on-line Python compiler

To find out which members attended both events, you may use the “intersection” method:

a = set(["Jake", "John", "Eric"])
b = set(["John", "Jill"])

print(a.intersection(b))
print(b.intersection(a))

Trinket.io on-line Python compiler

To find out which members attended only one of the events, use the “symmetric_difference” method:

a = set(["Jake", "John", "Eric"])
b = set(["John", "Jill"])

print(a.symmetric_difference(b))
print(b.symmetric_difference(a))

Trinket.io on-line Python compiler

To find out which members attended only one event and not the other, use the “difference” method:

a = set(["Jake", "John", "Eric"])
b = set(["John", "Jill"])

print(a.difference(b))
print(b.difference(a))

Trinket.io on-line Python compiler

To receive a list of all participants, use the “union” method:

a = set(["Jake", "John", "Eric"])
b = set(["John", "Jill"])

print(a.union(b))

Trinket.io on-line Python compiler

In the exercise below, use the given lists to print out a set containing all the participants from event A which did not attend event B.

# answer code: Try to figure it out on your
# own below using what you have learned thus far.
a = ["Jake", "John", "Eric"]
b = ["John", "Jill"]

A = set(a)
B = set(b)

print(A.difference(B))

Trinket.io on-line Python compiler

Connected through code, Choose Your Platform!

About the Author: Bernard Aybout

In the land of bytes and bits, a father of three sits, With a heart for tech and coding kits, in IT he never quits. At Magna's door, he took his stance, in Canada's wide expanse, At Karmax Heavy Stamping - Cosma's dance, he gave his career a chance. With a passion deep for teaching code, to the young minds he showed, The path where digital seeds are sowed, in critical thinking mode. But alas, not all was bright and fair, at Magna's lair, oh despair, Harassment, intimidation, a chilling air, made the workplace hard to bear. Management's maze and morale's dip, made our hero's spirit flip, In a demoralizing grip, his well-being began to slip. So he bid adieu to Magna's scene, from the division not so serene, Yet in tech, his interest keen, continues to inspire and convene.