PY-101 ยท Collections
Sets
โฑ 8 min ๐ Real Python 3 ๐ฌ Animated โ Completed
โก The 30-second answer
A set is an unordered collection of unique values in curly brackets, such as {"tea", "milk"}. Adding a value that is already there does nothing, so sets are the quickest way to remove duplicates. They also answer "what do these two groups share?" with & (intersection), | (union) and - (difference).
- Remove duplicates with set()
- Test membership with in
- Use &, | and -
Try it
Watch it come alive, run it yourself, then prove it. Real Python, right on this page.
Watch Python run the example. Every variable is a jar; watch the values change and the output appear.
emails = ["a@x.com", "b@x.com", "a@x.com", "c@x.com"]unique = set(emails)print(len(emails), "->", len(unique))team_a = {"Asha", "Ravi", "Li"}team_b = {"Ravi", "Li", "Sam"}print(sorted(team_a & team_b))print(sorted(team_a - team_b))print("Sam" in team_b)
Change anything and press Run (or Ctrl+Enter). Then open Watch it and press Watch my code.
Input one line per input() call
Press Run to see the output. Python runs in your browser. Expected output
4 -> 3
['Li', 'Ravi']
['Asha']
True ๐ฏ Print, sorted, the tags used in both posts (post1 & post2), then the tags used in either post, sorted.
Input one line per input() call
Press Run to see the output. Python runs in your browser. Need a hint?
print(sorted(post1 & post2)), then print(sorted(post1 | post2))
- The problemTwo teams sent you their attendee lists. Who came to both events? Who came only to one? With sets that is one line each.
- The Python idea
s = {a, b}A set is an unordered collection of unique values in curly brackets, such as {"tea", "milk"}. - In real lifeMarketing tools use set difference to find customers who signed up but never bought: signed_up - buyers.
Start with a question
Two teams sent you their attendee lists. Who came to both events? Who came only to one? With sets that is one line each.
De-duplicating emails, finding common customers and checking "have I seen this before?" are everyday data jobs.
Explain it like I'm 10
A set is a sticker album: each sticker can only be in it once. Get a second copy and it does not go in.
The technical explanation
set(["a", "b", "a"]) gives {"a", "b"}. Order is not kept, so you cannot index a set.
x in my_set is very fast even with millions of items.
a & b is items in both, a | b items in either, a - b items in a but not in b.
Syntax
s = {a, b}
s.add(x)
a & b a | b a - b Real-world scenario
Marketing tools use set difference to find customers who signed up but never bought: signed_up - buyers.
Test yourself
5 questions. Get 4 right and this lesson is marked complete.
Pass the quiz to complete this lesson.
๐ Every lesson counts toward your certificate Next: Dictionaries โQuestions people ask
How do I remove duplicates from a list in Python?
list(set(items)) removes duplicates but loses the order. To keep order use list(dict.fromkeys(items)).
Why is checking membership in a set faster than a list?
Sets use hashing, so Python jumps straight to where a value would be instead of checking every item.
Interview questions
How this topic comes up in Python interviews. Answer out loud first, then open the model answer.
beginner How do I remove duplicates from a list in Python?
list(set(items)) removes duplicates but loses the order. To keep order use list(dict.fromkeys(items)).
beginner Why is checking membership in a set faster than a list?
Sets use hashing, so Python jumps straight to where a value would be instead of checking every item.
intermediate len(set([1, 1, 2, 3, 3]))?
3. Duplicates are dropped: {1, 2, 3}.
intermediate How do you make an empty set?
set(). {} is an empty dict.
Quick revision
Remember
- Remove duplicates with set()
- Test membership with in
- Use &, | and -
{}is an empty dictionary, not an empty set. Writeset()for an empty set.
Syntax
s = {a, b}
s.add(x)
a & b a | b a - b Official documentation
- Sets (docs.python.org)