0% found this document useful (0 votes)
2 views8 pages

Python Sets

Uploaded by

23wh1db013
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views8 pages

Python Sets

Uploaded by

23wh1db013
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Python-Sets:

Why do we need Sets, when we have Lists and Tuples?

A Set is an unordered collection of unique elements.

● Written using curly braces { }.

● Duplicates are automatically removed.

● Unordered: No indexing or slicing.

● Mutable: You can add or remove elements.

● Heterogeneous: Can store different data types.

Characteristics of Sets

 Unordered (items do not have a fixed position)

 Mutable (you can add or remove items)

 Does not allow duplicate values

 Cannot access items using indexing

 Stores different data types

Creating a Set :

# Creating a set

fruits = {"apple", "banana", "cherry"}

print(fruits)

# Duplicates are removed

nums = {1, 2, 3, 2, 4, 1}

print(nums) # Output: {1, 2, 3, 4}

# Empty set

empty_set = set()

print(type(empty_set)) # <class 'set'>


# Wrong way (creates dictionary)

wrong = {}

print(type(wrong)) # <class 'dict'>

Why do we need sets?

● Want to store unique items (no duplicates).

● Need to perform mathematical set operations (union, intersection, etc.).

● Don’t care about order of elements.

Examples in real life:

● Unique usernames

● Unique tags or hashtags

● Removing duplicates from data

● Finding common friends/followers.

● Filtering unique words in text data.

● Comparing two datasets.

Duplicate Values are Removed Automatically


numbers = {10, 20, 30, 20, 10, 40}

print(numbers)

Output

{40, 10, 20, 30}


Accessing elements in sets:

Sets are unordered, so we can’t use indexing like s[0].

colors = {"red", "green", "blue"}

for c in colors:

print(c)

Creating an Empty Set

my_set = set()

print(type(my_set))

Output

<class 'set'>

Important: {} creates an empty dictionary, not an empty set.

Adding and Removing elements:

fruits = {"apple", "banana"}

# Add single element

[Link]("cherry")

print(fruits)

# Add multiple elements

[Link](["mango", "grapes"])

print(fruits)

# Remove element (KeyError if not present)

[Link]("banana")

# Discard element (No error if not present)

[Link]("kiwi")
# Remove a random element

[Link]()

# Clear all elements

[Link]()

# Delete entire set

# del fruits

Loop Through a Set

fruits = {"Apple", "Banana", "Orange"}

for fruit in fruits:


print(fruit)

Check if an Item Exists

fruits = {"Apple", "Banana", "Orange"}

if "Banana" in fruits:
print("Found")

Output

Found

Length of a Set

fruits = {"Apple", "Banana", "Orange"}

print(len(fruits))

Output

Set Operations:
A = {1, 2, 3, 4}

B = {3, 4, 5, 6}

# Union (all unique elements)

print(A | B)

print([Link](B))

# Intersection (common elements)

print(A & B)

print([Link](B))

# Difference (in A but not in B)

print(A - B)

print([Link](B))

# Symmetric Difference (elements not common)

print(A ^ B)

print(A.symmetric_difference(B))

Set functions and Methods:

nums = {10, 20, 30, 40, 50}

print(len(nums)) # Number of elements

print(max(nums)) # Maximum element

print(min(nums)) # Minimum element

print(sum(nums)) # Sum of all numbers

# Copy set

copy_set = [Link]()

print(copy_set)
Checking Membership:

colors = {"red", "blue", "green"}

print("red" in colors) # True

print("yellow" not in colors) # True

Frozen sets:

numbers = frozenset([1, 2, 3, 4])

# [Link](5) Error: can't modify frozen set

print(numbers)

Difference Between List, Tuple, and Set

Feature List Tuple Set

Symbol [] () {}

Ordered Yes Yes No

Mutable Yes No Yes

Duplicate Values Allowed Allowed Not Allowed

Indexing Yes Yes No

Example Program

students = {"Rahul", "Anitha", "Rahul", "Priya"}

print("Students:", students)

[Link]("Kiran")
print("After Adding:", students)
[Link]("Priya")
print("After Removing:", students)

print("Total Students:", len(students))

Sample Output

Students: {'Rahul', 'Anitha', 'Priya'}


After Adding: {'Rahul', 'Anitha', 'Priya', 'Kiran'}
After Removing: {'Rahul', 'Anitha', 'Kiran'}
Total Students: 3

Real-Life Applications of Sets

 Removing duplicate names from a student list

 Finding common subjects chosen by two students

 Identifying unique visitors to a website

 Removing duplicate email addresses

 Performing mathematical set operations

You might also like