01-12-2024
Module 3
Page 2
Module 3
► SELECTION AND ITERATION USING PYTHON:- if-else, elif, for loop, range, while loop.
► SEQUENCE DATA TYPES IN PYTHON -list, tuple, set, strings, dictionary, Creating and
using Arrays in Python (using Numpy library).
► DECOMPOSITION AND MODULARIZATION* :- Problem decomposition as a strategy for
solving complex problems, Modularization, Motivation for modularization, Defining and
using functions in Python, Functions with multiple return values
Page 3
1
01-12-2024
Python Set
Page 4
What is a Set?
► A set is a collection data type that is unordered, unique, mutable
(changeable), and unindexed.
► Unordered: The items do not have a defined order, so they do not maintain the
sequence in which they were added.
► Unique: A set cannot contain duplicate items. If duplicates are added, they will
automatically be removed.
► Mutable: Sets can be changed after they are created, allowing elements to be added or
removed.
► Unindexed: set do not have a specific position or index number.
► Unlike lists or tuples, where each element has a fixed position that you can access using an
index (like list[0] to get the first item), sets do not support this kind of indexing.
Page 4
2
01-12-2024
Creating a Set
► In Python, sets can be created in two main ways:
► Using curly braces {}
► my_set = {1, 2, 3}
► Using the set() function
► my_set = set([1, 2, 3])
Page 5
Creating an Empty Set
► In Python, curly braces {} are used to create both dictionaries and sets.
► However, when you write {} alone, Python interprets it as an empty dictionary rather
than an empty set.
► To create an empty set, you need to use the set() function.
► If you write set() with parentheses, Python understands this as an empty set.
# Empty set
empty_set = set()
print(type(empty_set)) # Output: <class 'set'>
Page 6
3
01-12-2024
Basic Set Operations
Page 7
Basic Set Operations
Operation Explanation Example
A = {1, 2, 3}
Add (add()) Adds a single specified element to the set. A.add(4)
Output: {1, 2, 3, 4}
A = {1, 2, 3}
Adds multiple elements from another set or iterable (like a list) to
Update (update()) A.update([4, 5, 6])
the set.
Output: {1, 2, 3, 4, 5, 6}
A = {1, 2, 3}
Removes a specific element from the set; raises an error if the
Remove (remove()) A.remove(2)
element is not found.
Output: {1, 3}
A = {1, 2, 3}
Removes a specific element from the set, but does not raise an
Discard (discard()) A.discard(4)
error if it’s missing.
Output: {1, 2, 3}
A = {1, 2, 3}
A.pop()
Pop (pop()) Removes and returns an arbitrary element from the set.
Output: {2, 3} (removes one item
randomly)
A = {1, 2, 3}
Clear (clear()) Removes all elements from the set, making it empty. A.clear()
Output: set() (an empty set)
Page 8
4
01-12-2024
Iterating through a Set
► To iterate through a set in Python, you can use a for loop.
► Since sets are unordered collections, the items do not have a specific order when
you iterate over them.
# Define a set with some values
my_set = {10, 20, 30, 40, 50}
40
10
# Use a for loop to iterate through the set
50
for item in my_set:
20
print(item)
30
Note: The order in which items are printed may differ when you run the program because sets do
not maintain a fixed order.
Page 9
Common Set Operations
Page 11
5
01-12-2024
Common Set Operations
► Python sets support various operations inspired by mathematical set theory
► Union (| or union())
► Combines all elements from two sets, returning a new set with all unique elements from
both.
A = {1, 2, 3}
B = {3, 4, 5}
C = A | B # or A.union(B)
print(C) # Output: {1, 2, 3, 4, 5}
Page 11
Common Set Operations
► Python sets support various operations inspired by mathematical set theory
► Intersection (& or intersection())
► Returns a new set containing only the elements found in both sets.
A = {1, 2, 3}
B = {3, 4, 5}
C = A & B # or A.intersection(B)
print(C) # Output: {3}
Page 12
6
01-12-2024
Common Set Operations
► Python sets support various operations inspired by mathematical set theory
► Difference (-or difference())
► Returns a new set with elements that are in the first set but not in the second.
A = {1, 2, 3}
B = {3, 4, 5}
C = A - B # or A.difference(B)
print(C) # Output: {1, 2}
Page 13
Common Set Operations
► Python sets support various operations inspired by mathematical set theory
► Symmetric Difference (^ or symmetric_difference())
► Returns a new set containing elements found in either of the sets but not in both.
A = {1, 2, 3}
B = {3, 4, 5}
C = A ^ B # or A.symmetric_difference(B)
print(C) # Output: {1, 2, 4, 5}
Page 14
7
01-12-2024
Why Use Sets?
► Sets are useful in situations where:
► Duplicate items are unnecessary: If you need to ensure only unique items, sets
automatically handle duplicates for you.
► Membership Testing: Checking if an item is in a set is generally faster than in lists or
tuples due to the underlying data structure.
► Set Operations: If you need to perform union, intersection, or difference, sets make
these tasks straightforward.
Page 15
Class Room Exercises
Page 16
8
01-12-2024
Class Room Exercises
Exercise 1: Unique Customer Visits
► Problem: A store wants to track the unique customer IDs of people who visit
each day. Each customer has a unique ID, and some customers visit more
than once a day. Create a program that adds customer IDs to a set, then
displays the unique customers for the day.
► Instructions
► Use add() to add customer IDs
to a set.
► Display the set to see all
unique customer IDs.
Page 17
Class Room Exercises
Exercise 2: Updating Inventory with New Items
► Problem: A shop has an initial inventory of items but receives a shipment
with new items. Update the inventory with the new items, ensuring there are
no duplicate entries.
► Instructions
► Create a set for the current inventory.
► Use update() to add new items from a
shipment.
► Display the updated inventory.
Page 18
9
01-12-2024
Class Room Exercises
Exercise 3: Removing Out-of-Stock Items
► Problem: The store wants to remove specific items from the inventory when
they are out of stock. Use remove() or discard() to handle this.
► Instructions
► Create a set with current stock items.
► Use remove() to remove an item that’s out of stock.
► Try to use discard() to remove another item (including one that might not exist).
Page 19
10
01-12-2024
Class Room Exercises
Exercise 4: Drawing a Random Winner from Participants
► Problem: A school is organizing a raffle with unique student IDs. Write a
program to randomly select a winner from the list of participants using
pop().
► Instructions
► Add student IDs to a set.
► Use pop() to randomly
remove and display a
winner.
► Ensure the winner is
removed from the set.
Page 21
Class Room Exercises
Exercise 5: Clearing Expired Discounts
► Problem: A store has a set of discount codes, but all codes have expired, so
they need to be removed. Write a program to clear the discount codes.
► Instructions
► Create a set of discount codes.
► Use clear() to remove all codes.
► Display the set to confirm it’s empty.
Page 22
11
01-12-2024
Class Room Exercises
Exercise 6: Removing a Product that Failed Quality Check
► Problem: A warehouse has a set of products ready for shipment, but one
product fails the quality check and must be removed. Use discard() to
remove it safely without raising an error if it’s missing.
► Instructions
► Create a set of product IDs.
► Use discard() to remove a
failed product.
► Print the set to see the
updated list of products.
Page 23
12