Lessons
Courses

Set in Python [ English ]

1. Introduction

A set in Python is a collection of unique elements. It is used when you want to store non-duplicate values.

Sets are:

  • Unordered (no fixed position/index)
  • Mutable (can be changed)
  • Do not allow duplicate values

2. Creating a Set

Syntax

set_name = {elements}

Example

numbers = {1, 2, 3, 4}names = {"Amit", "Rahul", "Priya"}

Creating an Empty Set

s = set()

👉 {} creates a dictionary, not a set.


3. Characteristics of Set

  • No duplicate elements
  • Unordered (no indexing)
  • Mutable (can add/remove items)
  • Elements must be immutable (int, string, tuple allowed)

4. Accessing Elements

Sets do not support indexing or slicing.

numbers = {1, 2, 3} for n in numbers: print(n)

5. Adding Elements

Using add()

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

Using update()

numbers.update([4, 5])

6. Removing Elements

Using remove()

numbers.remove(2)

Using discard()

numbers.discard(10)

Using pop()

numbers.pop()

👉 Removes a random element


7. Set Operations


7.1 Union (|)

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

Output

{1, 2, 3}

7.2 Intersection (&)

print(a & b)

Output

{2}

7.3 Difference (-)

print(a - b)

Output

{1}

7.4 Symmetric Difference (^)

print(a ^ b)

Output

{1, 3}

8. Membership Operators

print(2 in {1, 2, 3})print(5 not in {1, 2, 3})

9. Frozen Set

A frozen set is an immutable version of a set.

fs = frozenset([1, 2, 3])

👉 Cannot be modified


10. Built-in Functions

FunctionDescription
len()Number of elements
max()Maximum value
min()Minimum value
sum()Sum of elements

11. Example Program

a = {1, 2, 3}b = {2, 3, 4} print("Union:", a | b)print("Intersection:", a & b)print("Difference:", a - b)

12. Important Points

  • Sets are unordered and unindexed
  • Do not allow duplicates
  • Useful for mathematical operations
  • Cannot store mutable elements like lists

13. Summary

  • A set is a collection of unique elements

  • Created using {} or set()

  • Supports:

    • add/remove operations
    • union, intersection, difference
  • Does not support indexing

  • Useful for removing duplicates and performing set operations