Sets
A set stores unique values with no order. Use add, remove and discard. Set operations: | (union), & (intersection), - (difference) and ^ (symmetric difference). Turning a list into a set removes duplicates.
Example
tags = {"python", "sql", "python"}
print(len(tags))
tags.add("html")
print("sql" in tags)
a = {1, 2, 3}
b = {3, 4}
print(a | b)
print(a & b)
print(a - b)
print(sorted(set([3, 1, 3, 2, 1])))Result
2
True
{1, 2, 3, 4}
{3}
{1, 2}
[1, 2, 3]Exercise
Find the values in both sets.
print(a b)
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.