Sets

Sets store unordered collections of unique items.

Syntaxcolors = {'red', 'green'}

A set is an unordered collection of unique items. Write it with curly braces. Duplicates are automatically removed.

What sets are good for

  • Removing duplicates from a list.
  • Fast membership tests with in.
  • Maths-style operations: union |, intersection &, difference -.

Example

Example · python
nums = [1, 2, 2, 3, 3, 3]
unique = set(nums)
print(unique)

a = {1, 2, 3}
b = {2, 3, 4}
print(a & b)
print(a | b)

# Output:
# {1, 2, 3}
# {2, 3}
# {1, 2, 3, 4}

When to use it

  • A visitor counter stores user IDs in a set so duplicate visits are automatically ignored.
  • A search engine computes the intersection of two tag sets to find articles matching all keywords.
  • A de-duplicator converts a list of emails to a set and back to remove all repeated entries.

More examples

Create a set and add items

Shows that adding a duplicate element to a set has no effect, enforcing uniqueness.

Example · python
visited = {'home', 'about', 'contact'}
visited.add('blog')
visited.add('home')   # duplicate, ignored
print(visited)
# {'home', 'about', 'contact', 'blog'}  (order varies)

Set operations

Uses &, |, and - operators to find common, combined, and exclusive members.

Example · python
python_devs = {'Alice', 'Bob', 'Carol'}
js_devs = {'Bob', 'Carol', 'Dave'}

print(python_devs & js_devs)   # intersection: {'Bob', 'Carol'}
print(python_devs | js_devs)   # union: all four
print(python_devs - js_devs)   # difference: {'Alice'}

Remove duplicates from a list

Converts a list to a set to remove duplicates, then back to a sorted list.

Example · python
emails = ['[email protected]', '[email protected]', '[email protected]', '[email protected]']
unique = list(set(emails))
print(len(unique))   # 3
print(sorted(unique))
# ['[email protected]', '[email protected]', '[email protected]']

Discussion

  • Be the first to comment on this lesson.