Set operations

Dictionaries & Sets, lesson 5 of 5

🗂️ Dictionaries & Sets, lesson 5 of 5

Set operations

Combine and compare sets: union, intersection and difference.

9 min

1 exercise

2 quizzes

0/3 solved

Getting Python ready… examples can run in a moment.

Sets shine when you compare groups:

  • a | b union: in either set
  • a & b intersection: in both
  • a - b difference: in a but not b
  • a ^ b symmetric difference: in exactly one
  • a <= b subset: is everything in a also in b?
Example

Friends in common

Is ana - ben the same as ben - ana? Try it.

Example

Missing ingredients

Add "eggs" and "milk" to the pantry and run it again.

Quiz

What does this print?

Example

Fast membership

word in blocked stays fast for a set, even with a million entries. With a list, Python has to check the items one by one.

Quiz

You need to look up each student's phone number by their name. Which collection fits best?

Exercise

Team skills

Use set operators to compute:

  1. shared: skills Alice and Bob both have
  2. team: every skill either of them has
  3. alice_missing: skills the job needs that Alice doesn't have
  4. covered: True if the team together has every skill the job needs