Notes
Categories

Set in Python [ English ]

< Prev Next >

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:


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


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

Function Description
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


13. Summary

< Prev Next >