LearnFrenzy
Sign in Take a free test

Python Programming · Topic 9 of 25

Sets Questions and Concepts

  • 4 exercises
  • 50 questions
  • ~60 min
  • Answers explained

Introduction & Syntax

Sets · Study material

A set is an unordered collection of unique, hashable items. Sets answer questions that lists answer slowly: Is this user already registered? Which students take both courses? Which tags are new? Membership tests on a set are fast however big it gets, and the maths operations – union, intersection, difference – are one operator each. Tests probe the traps: {} is a dict, sets cannot be indexed, 1 and True are the same element, and remove() differs from discard(). This topic covers it all, then 50 practice questions run on Python 3.

On this page

  • Creating sets – and why {} is not one
  • Adding and removing: add, update, remove, discard, pop
  • Union, intersection, difference, symmetric difference
  • Subset, superset and disjoint tests
  • Hashable elements, frozenset and set comprehensions
  • Removing duplicates, with and without keeping order

Creating sets

Write items in braces, or convert an iterable with set() – duplicates are dropped automatically. {} creates an empty dictionary; an empty set is set(). Sets have no order and no indexes: s[0] is a TypeError, and the order you see when printing is not something to rely on (for strings it can even change from one run to the next). Sort a set when you need a fixed order.

primes = {2, 3, 5, 7}
digits = set([1, 2, 2, 3, 3, 3])        # duplicates disappear
letters = set("banana")                # set of the characters
empty = set()                          # {} would be an empty DICT

print(primes, digits, len(digits))
print(sorted(letters), type({}).__name__, type(empty).__name__)
print(5 in primes, 4 not in primes)

Output

{2, 3, 5, 7} {1, 2, 3} 3
['a', 'b', 'n'] dict set
True True

Adding and removing elements

add(x) inserts one element; update(iterable, …) inserts many. remove(x) raises KeyError if x is missing, discard(x) does not. pop() removes and returns an arbitrary element (KeyError on an empty set), and clear() empties the set.

ids = {101, 102}
ids.add(103)               # one element
ids.add(101)               # already present: nothing happens
ids.update([104, 105], (106,))   # many elements from iterables
print(ids)

ids.remove(106)            # KeyError if absent
ids.discard(999)           # silently ignores a missing element
print(ids, len(ids))

ids.clear()
print(ids)

Output

{101, 102, 103, 104, 105, 106}
{101, 102, 103, 104, 105} 5
set()

Set operations

OperationOperatorMethodResult
Uniona | ba.union(b)in a or b
Intersectiona & ba.intersection(b)in both
Differencea - ba.difference(b)in a but not b
Symmetric differencea ^ ba.symmetric_difference(b)in exactly one

Operators need sets on both sides; methods accept any iterable. Each has an in-place form (|=, &=, -=, ^= or update(), intersection_update() …). The plain methods return a new set and leave the original unchanged.

python = {1, 2, 3, 4}       # roll numbers enrolled in Python
java = {3, 4, 5}            # … and in Java

print(python | java)        # union: in either
print(python & java)        # intersection: in both
print(python - java)        # difference: Python only
print(java - python)        # (order matters for difference)
print(python ^ java)        # symmetric difference: in exactly one

print(python.union([9]), python.intersection(range(3, 10)))   # methods accept any iterable

Output

{1, 2, 3, 4, 5}
{3, 4}
{1, 2}
{5}
{1, 2, 5}
{1, 2, 3, 4, 9} {3, 4}

Subset, superset and disjoint

a <= b (issubset) – every element of a is in b; a < b – subset and not equal. >= and > are the superset tests, and isdisjoint() checks that two sets share nothing. Two sets are equal when they have the same elements, regardless of order.

required = {"python", "sql"}
skills = {"python", "sql", "git"}

print(required <= skills, required.issubset(skills))   # subset
print(skills >= required, skills.issuperset(required)) # superset
print(required < skills, skills < skills)              # proper subset: not equal
print(required.isdisjoint({"java", "c"}))              # no common element
print(sorted(skills - required))

Output

True True
True True
True False
True
['git']

Only hashable elements

Set elements must be hashable: numbers, strings, tuples of hashable items and frozensets are; lists, dicts and sets are not. Because 1 == True == 1.0 and they hash equally, a set keeps only one of them – the first one added.

s = {1, "a", (2, 3), 4.5}           # numbers, strings, tuples: all hashable
print(len(s))

try:
    {[1, 2]}                        # a list is mutable, so it cannot be in a set
except TypeError as e:
    print("TypeError:", e)

print({1, True, 1.0, 2})            # 1 == True == 1.0 with the same hash: ONE element
print(len({0, False, 0.0, ""}))

Output

4
TypeError: unhashable type: 'list'
{1, 2}
2

frozenset and set comprehensions

A frozenset is an immutable set, so it can be a dictionary key or an element of another set – useful for unordered pairs. A set comprehension {expr for x in it if cond} builds a set in one line.

pair = frozenset({"Delhi", "Agra"})     # immutable set: hashable
routes = {pair: 233}
print(routes[frozenset({"Agra", "Delhi"})])   # order does not matter

squares = {n * n for n in range(-3, 4)}       # set comprehension
print(sorted(squares))

words = ["Hi", "hi", "HELLO", "hello", "hey"]
print(sorted({w.lower() for w in words}))

Output

233
[0, 1, 4, 9]
['hello', 'hey', 'hi']

Common mistakes

  • s = {} then s.add(x) – {} is a dict: AttributeError.
  • Indexing a set – s[0] is a TypeError; convert or sort first.
  • Expecting insertion order – use dict.fromkeys() to dedupe in order.
  • remove() on a missing element – KeyError; use discard().
  • a + b – sets use | for union.
  • Calling a.union(b) and ignoring the result – a is unchanged; use a |= b.
  • Putting lists in a set – convert them to tuples.

Key points to remember

  • Sets hold unique, hashable items with no order and no index.
  • set() is empty; {} is an empty dict.
  • Membership tests are O(1) on average.
  • | & - ^ give union, intersection, difference, symmetric difference.
  • remove raises KeyError; discard does not.
  • 1, True and 1.0 count as the same element.
  • frozenset is the immutable, hashable set.

Frequently asked questions

Why is checking "x in set" faster than "x in list"?

A set finds x through its hash in roughly constant time; a list must compare items one by one (O(n)).

Does a set keep insertion order?

No – unlike dict, set order is an implementation detail. For an ordered unique collection use dict.fromkeys(items).

Can a set contain another set?

Only a frozenset, because a normal set is mutable and therefore unhashable.

Where can I learn more?

Read Python Sets and Choosing the Right Collection in the Python tutorial, then practise with the exercises below.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About Python Programming

Why it matters

  • Python is the most popular first language and the default for data science, AI, automation and scripting
  • Campus coding rounds and technical interviews increasingly allow – or prefer – Python
  • "Predict the output" questions on lists, strings, dictionaries and mutable defaults are a favourite in written tests
  • Clean Python with comprehensions, generators and OOP is what product companies expect from freshers

Who it is for

  • School students (Class 11–12 computer science with Python) preparing for board exams and practicals
  • College students (B.Tech, BCA, MCA, B.Sc CS) preparing for semester exams, lab work and viva
  • Freshers preparing for campus placements, coding tests and Python interviews
  • Anyone moving into data science, AI or automation who needs strong Python fundamentals

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • Topic-wise MCQs that check your understanding of every concept
  • "Predict the output" puzzles – the trickiest part of written tests
  • "Find the error" programs: syntax errors, runtime exceptions and logical bugs
  • Coding problems with solutions and real output, every one run on Python 3 – open any example in the online Python compiler

Asked in

  • Campus placements
  • TCS, Infosys, Wipro, Accenture tests
  • Python interviews for freshers
  • Data science interviews
  • CBSE / university practicals
  • GATE CS

How to use this section

  1. Read the study material of a topic and run the examples in the browser.
  2. Practise the four exercises – MCQs, output, errors, coding problems – each marked Easy, Medium or Hard, and read every explanation.
  3. Revise with the interview questions and cheat sheet, then move to the next topic.

Search LearnFrenzy

Esc

Quick links