0% found this document useful (0 votes)
4 views20 pages

Sets in Python

This document provides a comprehensive overview of sets in Python, including their definition, characteristics, and methods for manipulation. It covers set operations such as union, intersection, and difference, along with examples and outputs for each method. Additionally, it includes multiple-choice questions to test understanding of set functionalities.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views20 pages

Sets in Python

This document provides a comprehensive overview of sets in Python, including their definition, characteristics, and methods for manipulation. It covers set operations such as union, intersection, and difference, along with examples and outputs for each method. Additionally, it includes multiple-choice questions to test understanding of set functionalities.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

1.

Definition and Introduction to Sets in Python


What is a Set?

 A Set is an unordered, unindexed, and mutable collection of unique elements.


 Defined using curly braces {} or the set() constructor.

my_set = {1, 2, 3}
another_set = set([1, 2, 3])

2. Characteristics of Sets
 No duplicates allowed.
 Unordered – elements don’t maintain insertion order.
 Mutable – can add or remove items.
 Supports mathematical set operations.

3. Removing Duplicates using Set


my_list = [1, 2, 2, 3, 4, 4]
unique = list(set(my_list))
print(unique)

Output:

[1, 2, 3, 4]

✔ Converts list to set to remove duplicates, then back to list.

4. Set Operations Table in Python (with Example & Output)


Operation Symbol / Method Description Example Output
Union | or.union()` All unique elements {1, 2}.union({2, 3}) {1, 2}
from both sets
Intersection & or .intersection() Elements common to {1, 2, 3} & {2, 3, 4} {2, 3}
both sets
Difference - or .difference() Elements in the first set {1, 2, 3} - {2, 3} {1}
but not in the second
Symmetric ^ or Elements in either set {1, 2} ^ {2, 3} {1, 3}
Difference .symmetric_difference() but not in both
Subset .issubset() Checks if set is a subset {1, 2}.issubset({1, 2, 3}) True
of another
Superset .issuperset() Checks if set is a {1, 2, 3}.issuperset({1, 2}) True
superset of another
Disjoint .isdisjoint() Checks if sets have no {1, 2}.isdisjoint({3, 4}) True
elements in common
Examples:
a = {1, 2, 3}
b = {3, 4, 5}
print(a | b) # Union
print(a & b) # Intersection
print(a - b) # Difference
print(a ^ b) # Symmetric Difference
print(a.issubset(b)) # Subset?
print(a.issuperset({1, 2})) # Superset?
print(a.isdisjoint({4, 5})) # Disjoint?

Output:

{1, 2, 3, 4, 5}
{3}
{1, 2}
{1, 2, 4, 5}
False
True
True

5. Set Methods – Syntax, Examples, Outputs, Explanations


Method Syntax Explanation
add() s.add(x) Adds element x to the set
update() s.update([iterable]) Adds multiple elements
remove() s.remove(x) Removes x, throws error if not found
discard() s.discard(x) Removes x, no error if not found
pop() s.pop() Removes random item
clear() s.clear() Empties the set
copy() s.copy() Returns a shallow copy of the set
union() s.union(t) Returns union of two sets
intersection() s.intersection(t) Returns intersection
difference() s.difference(t) Returns difference
symmetric_difference() s.symmetric_difference(t) Returns symmetric difference
issubset() s.issubset(t) Checks if s is subset of t
issuperset() s.issuperset(t) Checks if s is superset of t
isdisjoint() s.isdisjoint(t) Checks if sets are disjoint

Python Set Methods Table (with Example & Output)


Syntax Explanation Example Output
s.add(x) Adds element x to s = {1, 2}; s.add(3); {1, 2, 3}
print(s)
the set
s.update([iterable]) Adds multiple s = {1}; s.update([2, 3]); {1, 2, 3}
print(s)
elements to the set
s.remove(x) Removes x; throws s = {1, 2}; s.remove(2); {1}
print(s)
error if not found
s.discard(x) Removes x; no error s = {1, 2}; s.discard(3); {1, 2}
print(s)
if not found
s.pop() Removes and returns s = {1, 2, 3}; s.pop(); Random
print(s)
a random item element
removed
s.clear() Empties the set s = {1, 2}; s.clear(); set()
print(s)
s.copy() Returns a shallow s = {1, 2}; c = s.copy(); {1, 2}
print(c)
copy
s.union(t) Returns union of sets {1, 2}.union({2, 3}) {1, 2, 3}
s and t
s.intersection(t) Returns common {1, 2, 3}.intersection({2, {2}
4})
elements
s.difference(t) Elements in s but not {1, 2, 3}.difference({2}) {1, 3}
in t
s.symmetric_difference(t) Elements in either set {1, {1, 3}
2}.symmetric_difference({2,
but not both
3})
s.issubset(t) Checks if s is subset {1, 2}.issubset({1, 2, 3}) True
of t
s.issuperset(t) Checks if s is {1, 2, 3}.issuperset({1, 2}) True
superset of t
s.isdisjoint(t) Checks if sets have {1, 2}.isdisjoint({3, 4}) True
no elements in
common

6. Examples for Each Set Method


add()

s = {1, 2}
s.add(3)
print(s)

Output: {1, 2, 3}

update()

s = {1}
s.update([2, 3])
print(s)

Output: {1, 2, 3}

remove() vs discard()
s = {1, 2}
s.remove(1)
s.discard(3) # No error
print(s)

Output: {2}

pop()

s = {1, 2, 3}
print(s.pop()) # Random element removed
print(s)

clear()

s = {1, 2, 3}
s.clear()
print(s)

Output: set()

copy()

s = {1, 2}
t = s.copy()
t.add(3)
print(s, t)

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

union() and intersection()


a = {1, 2}
b = {2, 3}
print(a.union(b))
print(a.intersection(b))

Output:

{1, 2, 3}
{2}

difference()

print({1, 2, 3}.difference({2}))

Output: {1, 3}
symmetric_difference()

print({1, 2}.symmetric_difference({2, 3}))

Output: {1, 3}

issubset() and issuperset()


print({1, 2}.issubset({1, 2, 3}))
print({1, 2, 3}.issuperset({1}))

Output:

True
True

isdisjoint()

print({1, 2}.isdisjoint({3, 4}))

Output: True

Summary Table of Set Methods


Method Modifies Set? Returns Value? Safe for Missing?
add Yes No Yes
update Yes No Yes
remove Yes No No (Error)
discard Yes No Yes
pop Yes Yes No (Error if empty)
clear Yes No Yes
copy No Yes Yes

MCQ 1

What is the output of the following code?

s = {1, 2, 3}
s.add(4)
print(s)
A) {1, 2, 3}
B) {4, 2, 1}
C) {1, 2, 3, 4}
D) Error

Answer: C
Explanation: add() adds an element to the set.

MCQ 2

Which method is used to remove a specific element from a set without throwing an error if the element is not
found?

A) remove()
B) delete()
C) discard()
D) pop()

Answer: C
Explanation: discard() safely removes an element if it exists, otherwise does nothing.

MCQ 3

What does the update() method do?

A) Adds a single element


B) Removes an element
C) Adds multiple elements from an iterable
D) Replaces elements in a set

Answer: C
Explanation: update() takes an iterable and adds each element.

MCQ 4

Which of the following will raise a KeyError if the element is not found?

A) remove()
B) discard()
C) update()
D) pop()

Answer: A
Explanation: remove() raises an error if the element is not present.
MCQ 5

What is the output of:

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

A) {3}
B) {1, 2, 3, 4}
C) {1, 2}
D) Error

Answer: A
Explanation: & is the intersection operator; only 3 is common.

MCQ 6

Which of the following will return a new set with all elements from both sets?

A) a - b
B) a.union(b)
C) a & b
D) a.intersection(b)

Answer: B
Explanation: union() returns a set containing all elements from both sets.

MCQ 7

What does the clear() method do?

A) Deletes the set


B) Removes a random element
C) Removes all elements from the set
D) Returns a new empty set

Answer: C
Explanation: clear() empties the set in-place.

MCQ 8

What is the output?


{1, 2, 3}.difference({2, 3})

A) {1}
B) {2, 3}
C) {1, 2, 3}
D) {}

Answer: A
Explanation: difference() returns elements only in the first set.

MCQ 9

Which method returns True if two sets have no elements in common?

A) issubset()
B) isdisjoint()
C) issuperset()
D) intersection()

Answer: B
Explanation: isdisjoint() returns True if sets are completely separate.

MCQ 10

What is the result of this?

a = {1, 2}
b = {2, 3}
print(a ^ b)

A) {1, 2, 3}
B) {1, 3}
C) {2}
D) {}

Answer: B
Explanation: ^ is symmetric difference (elements in either set but not both).

MCQ 11

Which method is used to copy a set?

A) copyset()
B) clone()
C) copy()
D) setcopy()

Answer: C
Explanation: copy() returns a shallow copy of the set.

MCQ 12

What does pop() do in sets?

A) Removes the last element


B) Removes a random element
C) Removes the smallest element
D) Always raises an error

Answer: B
Explanation: Sets are unordered, so pop() removes a random element.

MCQ 13

Which method returns True if one set is a subset of another?

A) subset()
B) issubset()
C) checksubset()
D) ispartof()

Answer: B
Explanation: issubset() checks if all elements of one set are in another.

MCQ 14

What is the output of:

a = {1, 2}
b = {1, 2, 3}
print(a.issubset(b))

A) True
B) False
C) Error
D) None

Answer: A
Explanation: All elements of a exist in b.
MCQ 15

Which is not a valid set method?

A) add()
B) push()
C) discard()
D) union()

Answer: B
Explanation: push() is not a set method in Python.

MCQ 16

What happens when you do:

a = {1, 2}
a.add(2)
print(a)

A) {1}
B) {2}
C) {1, 2}
D) Error

Answer: C
Explanation: Adding an existing element has no effect in a set.

MCQ 17

Which statement about sets is false?

A) Sets are unordered


B) Sets allow duplicates
C) Sets are mutable
D) Sets can’t contain other sets

Answer: B
Explanation: Sets do not allow duplicate elements.

MCQ 18

What is the output of:


a = set("hello")
print(a)

A) {'hello'}
B) {'h', 'e', 'l', 'o'}
C) ['h', 'e', 'l', 'o']
D) ('h', 'e', 'l', 'o')

Answer: B
Explanation: Converts string into a set of unique characters.

MCQ 19

What is the output of:

a = {1, 2, 3}
b = a.copy()
b.add(4)
print(a, b)

A) {1, 2, 3} {1, 2, 3, 4}
B) {1, 2, 3, 4} {1, 2, 3}
C) {1, 2, 3} {1, 2, 3}
D) Error

Answer: A
Explanation: copy() creates a new set; modifying b doesn’t affect a.

MCQ 20

Which of the following will convert a list with duplicates into a list of unique items?

A) list(set(list))
B) set(list(list))
C) dict(set(list))
D) tuple(set(list))

Answer: A
Explanation: set() removes duplicates, then list() converts it back to list.

1. Create a set and print it


s = {1, 2, 3, 4}
print(s)
Output: {1, 2, 3, 4}
Explanation: Creates a set of integers.

2. Add single element to a set


s = {10, 20}
s.add(30)
print(s)

Output: {10, 20, 30}


add() inserts an element.

3. Add multiple elements to a set


s = {1}
s.update([2, 3, 4])
print(s)

Output: {1, 2, 3, 4}
update() adds multiple items from an iterable.

4. Remove an item using remove()


s = {1, 2, 3}
s.remove(2)
print(s)

Output: {1, 3}
remove() deletes an item; error if not found.

5. Remove an item using discard()


s = {1, 2, 3}
s.discard(5) # No error
print(s)

Output: {1, 2, 3}
discard() avoids error if item not found.

6. Remove a random item using pop()


s = {10, 20, 30}
removed = s.pop()
print(removed)

Output: 10 (or any element)


pop() removes a random element.

7. Clear all elements in a set


s = {1, 2, 3}
s.clear()
print(s)

Output: set()
Empties the set.

8. Copy a set
s = {5, 6}
t = s.copy()
t.add(7)
print(s, t)

Output: {5, 6} {5, 6, 7}


copy() makes a new set.

9. Find union of two sets


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

Output: {1, 2, 3}
|operator for union.

10. Find intersection of two sets


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

Output: {2}
Common elements.
11. Find difference of sets
a = {1, 2, 3}
b = {2, 4}
print(a - b)

Output: {1, 3}
Only in a, not in b.

12. Symmetric difference


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

Output: {1, 2, 4}
Elements in either a or b, but not both.

13. Check subset


a = {1, 2}
b = {1, 2, 3}
print(a.issubset(b))

Output: True
All elements of a exist in b.

14. Check superset


a = {1, 2, 3}
b = {2, 3}
print(a.issuperset(b))

Output: True
acontains all of b.

15. Check disjoint sets


a = {1, 2}
b = {3, 4}
print(a.isdisjoint(b))
Output: True
No common elements.

16. Remove duplicates from a list using set


lst = [1, 2, 2, 3, 4, 4]
print(list(set(lst)))

Output: [1, 2, 3, 4] (order may vary)


Converts list to set to remove duplicates.

17. Set from string characters


s = set("banana")
print(s)

Output: {'a', 'b', 'n'}


Only unique letters.

18. Set comprehension


squares = {x*x for x in range(5)}
print(squares)

Output: {0, 1, 4, 9, 16}


Set from expression.

19. Count unique elements using set


lst = [10, 20, 10, 30, 20]
print(len(set(lst)))

Output: 3
Number of distinct elements.

20. Convert tuple to set


t = (1, 2, 2, 3)
s = set(t)
print(s)
Output: {1, 2, 3}
Removes duplicates from tuple.

21. Convert a list of lists to a set of unique tuples


lst = [[1, 2], [2, 3], [1, 2]]
unique_tuples = set(tuple(x) for x in lst)
print(unique_tuples)

Output: {(1, 2), (2, 3)}


Tuples are hashable; list is not. Used tuple(x) to convert.

22. Count common elements between two sets


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

Output: 2
Uses intersection to count shared elements.

23. Get elements only in one set (not both)


a = {1, 2, 3}
b = {3, 4, 5}
print(a.symmetric_difference(b))

Output: {1, 2, 4, 5}
Symmetric difference.

24. Create set from numbers divisible by 3


s = {x for x in range(1, 20) if x % 3 == 0}
print(s)

Output: {3, 6, 9, 12, 15, 18}


Set comprehension with condition.

25. Check if all elements of a list are unique using set


lst = [1, 2, 3, 4, 4]
print(len(lst) == len(set(lst)))
Output: False
Duplicates shrink size after set conversion.

26. Find maximum and minimum in a set


s = {5, 1, 10, 3}
print(max(s), min(s))

Output: 10 1
Works as with any iterable.

27. Convert dictionary keys to set


d = {'a': 1, 'b': 2}
print(set(d))

Output: {'a', 'b'}


Keys are used in set conversion.

28. Check if one set is proper subset of another


a = {1, 2}
b = {1, 2, 3}
print(a < b)

Output: True
< checks proper subset (not equal).

29. Check if one set is proper superset of another


a = {1, 2, 3}
b = {1, 2}
print(a > b)

Output: True
> means strict superset.

30. Union multiple sets using union()


a = {1, 2}
b = {3}
c = {4, 5}
result = a.union(b, c)
print(result)

Output: {1, 2, 3, 4, 5}
Accepts multiple sets.

31. Find duplicate elements using sets


lst = [1, 2, 2, 3, 3, 3, 4]
seen = set()
duplicates = {x for x in lst if x in seen or seen.add(x)}
print(duplicates)

Output: {2, 3}
Clever trick using set and comprehension.

32. Find items common in 3 sets


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

Output: {2, 3}
Chain intersection.

33. Generate all possible union combinations


a = {1}
b = {2}
c = {3}
print(a | b | c)

Output: {1, 2, 3}
Multi-set union using |.

34. Check set length


s = {5, 6, 7}
print(len(s))

Output: 3
works on sets.
len()
35. Check for presence of an element
s = {1, 2, 3}
print(2 in s)

Output: True
Fast membership check.

36. Convert set to sorted list


s = {3, 1, 2}
print(sorted(s))

Output: [1, 2, 3]
sorted() gives sorted list.

37. Intersection using intersection() method


a = {1, 2, 3}
b = {2, 4}
print(a.intersection(b))

Output: {2}
Equivalent to a & b.

38. Find items only in first set


a = {10, 20, 30}
b = {20, 40}
print(a.difference(b))

Output: {10, 30}


a - b.

39. Count how many sets contain a given item


sets = [{1, 2}, {2, 3}, {2, 4}]
count = sum(1 for s in sets if 2 in s)
print(count)

Output: 3
Counting presence across sets.
40. Remove all elements greater than 10
s = {5, 10, 15, 20}
filtered = {x for x in s if x <= 10}
print(filtered)

Output: {10, 5}
Used set comprehension with condition.

You might also like