DEV Community

Jay
Jay

Posted on

Sets

Sets are lists with no duplicate entries.
Since the rest of the sentence uses words which are already in the set, they are not inserted twice.

print(set("I want it Pronto and I am late".split()))
Enter fullscreen mode Exit fullscreen mode

Sets are huge importance. When look for differences and intersections between other sets. For example, say you have a list of participants in events A and B:

a = set(["or", "ni", "car"])
print(a)
b = set(["oui", "non"])
print(b)
Enter fullscreen mode Exit fullscreen mode

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

a = set(["or", "ni", "car"])

b = set(["oui", "non"])


print(a.intersection(b))
print(b.intersection(a))
Enter fullscreen mode Exit fullscreen mode

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

a = set(["or", "ni", "car"])

b = set(["oui", "non"])


print(a.symmetric_difference(b))
print(b.symmetric_difference(a))
Enter fullscreen mode Exit fullscreen mode

To find out which members attended only one event and not the other, use the "difference" method:
To receive a list of all participants, use the "union" method:

a = set(["or", "ni", "car"])
b = set(["oui", "non"])

print(a.union(b))
Enter fullscreen mode Exit fullscreen mode

Top comments (0)