Sets and Set Methods

1. 🆔 Sets

    1.1 What is a Set?
    1. Imagine a website storing registered usernames. Each username must be unique. If "ram123" is already registered, adding "ram123" again does not create another user with the same username. A Python set works in a similar way. A set is a data type in Python used to store unique items in a single variable. A set is: ✅ Unordered ✅ Mutable ✅ Stores unique items only ✅ Written inside curly braces { } ✅ Useful for removing duplicates and comparing groups 👉 Unordered means items do not have a fixed position. 👉 Mutable means we can add or remove items after the set is created. 👉 Unique means duplicate values are stored only once. Example: usernames = {"ram123", "sita45", "ram123", "hari88"} print(usernames) # ➜ {"ram123", "sita45", "hari88"} 📌 The output order may be different because sets are unordered.
    1.2 Creating Sets
    1. Sets are created by placing items inside curly braces { } and separating them with commas. Examples: int_set = {1, 2, 3}str_set = {"apple", "banana", "orange"}mixed_set = {1, "hello", 3.14, True}print(int_set) print(str_set) print(mixed_set)
    1.3 Duplicate Values are Removed
    1. Sets do not store duplicate values. Example: my_set = {1, 2, 2, 3, 3, 3} print(my_set) # ➜ {1, 2, 3} Here, duplicate values are automatically removed.
    1.4 Creating an Empty Set
    1. We cannot create an empty set using { }. Example: empty_data = {} print(type(empty_data)) # ➜ <class 'dict'> To create an empty set, we use set(). Example: empty_set = set() print(type(empty_set)) # ➜ <class 'set'> 📌 { } creates an empty dictionary, not an empty set.
    1.5 Sets Can Store Only Immutable Items
    1. Set items must be immutable. This means we can store values like: NumbersStringsTuples But we cannot store mutable items like lists inside a set. Example: valid_set = {1, "hello", (1, 2)} print(valid_set)Invalid Example: my_set = {1, [2, 3]} # ➜ TypeError ⚠️ This line gives an error because list is mutable and cannot be stored inside a set. 📌 TypeError means Python cannot perform the operation because the data type is not suitable.

2. 🔎 Accessing and Checking Set Items

    2.1 Sets Do Not Support Indexing
    1. Sets are unordered, so items do not have fixed positions. Because of this, indexing is not allowed. Example: my_set = {"apple", "banana", "orange"} print(my_set[0]) # ➜ TypeError ⚠️ This line gives an error because set items cannot be accessed using index. 📌 Use a list or tuple when position matters. 📌 Use a set when uniqueness matters.
    2.2 Checking Membership using in
    1. We can check whether an item exists in a set using in. Example: my_set = {"apple", "banana", "orange"}print("apple" in my_set) # ➜ True print("mango" in my_set) # ➜ False
    2.3 Checking Non-Membership using not in
    1. We can check whether an item does not exist in a set using not in. Example: my_set = {"apple", "banana", "orange"}print("mango" not in my_set) # ➜ True print("banana" not in my_set) # ➜ False

3. ➕➖ Adding and Removing Set Items

    3.1 add()
    1. add() is used to add one item to a set. It modifies the original set. Example: my_set = {1, 2, 3}my_set.add(4) print(my_set) # ➜ {1, 2, 3, 4} my_set.add(2) print(my_set) # ➜ {1, 2, 3, 4} 📌 Adding a duplicate value does not change the set.
    3.2 update()
    1. update() is used to add multiple items from another iterable such as a list, tuple, or set. It modifies the original set. Example: my_set = {1, 2, 3}my_set.update([4, 5]) print(my_set) # ➜ {1, 2, 3, 4, 5} my_set.update((6, 7)) print(my_set) # ➜ {1, 2, 3, 4, 5, 6, 7} my_set.update({8, 9}) print(my_set) # ➜ {1, 2, 3, 4, 5, 6, 7, 8, 9} 📌 add() adds one item. 📌 update() adds multiple items.
    3.3 update() with String
    1. A string is also an iterable. So if we use update() with a string, each character is added separately. Example: my_set = {1, 2, 3}my_set.update("hi") print(my_set) # ➜ {1, 2, 3, "h", "i"} 📌 The output order may be different because sets are unordered.
    3.4 remove()
    1. remove() removes a specified item from a set. It gives an error if the item is not found. Example: my_set = {1, 2, 3, 4}my_set.remove(2) print(my_set) # ➜ {1, 3, 4} my_set.remove(5) # ➜ KeyError ⚠️ This line gives an error because 5 is not found in the set. 📌 KeyError means Python could not find the requested value in the set.
    3.5 discard()
    1. discard() also removes a specified item from a set. But it does not give an error if the item is not found. Example: my_set = {1, 2, 3, 4}my_set.discard(3) print(my_set) # ➜ {1, 2, 4} my_set.discard(5) print(my_set) # ➜ {1, 2, 4} 📌 remove() gives an error if the item is not found. 📌 discard() does not give an error if the item is not found.
    3.6 pop()
    1. pop() removes and returns one item from a set. Since sets are unordered, we cannot know which item will be removed. Example: my_set = {1, 2, 3, 4}removed_item = my_set.pop() print(removed_item) # ➜ Could be any item from the set print(my_set) # ➜ Set with one less item 📌 In lists, pop() usually removes the last item. 📌 In sets, pop() removes an arbitrary item because sets are unordered.

4. 🧮 Common Set Functions

    4.1 Numeric and Common Functions
    1. Some functions are useful for numeric sets, while others work with any set. Common Functions: sum() ➜ Adds all numbers min() ➜ Finds smallest value max() ➜ Finds largest value len() ➜ Counts number of unique items sorted() ➜ Returns a sorted list copy() ➜ Creates a copy of a set 📌 sum() works only with numeric sets. 📌 min() and max() work when the set items can be compared with each other.
    4.2 Numeric Function Examples
    1. num_set = {1, 2, 3, 4, 5}print(sum(num_set)) # ➜ 15 print(min(num_set)) # ➜ 1 print(max(num_set)) # ➜ 5 print(len(num_set)) # ➜ 5
    4.3 sorted()
    1. Sets do not have a fixed order. If we want sorted output, we can use sorted(). sorted() returns a list, not a set. Example: my_set = {3, 1, 4, 2}sorted_data = sorted(my_set) print(sorted_data) # ➜ [1, 2, 3, 4] print(type(sorted_data)) # ➜ <class 'list'> 📌 sorted() does not change the original set. 📌 sorted() returns a list.
    4.4 Sorting Strings
    1. Example: str_set = {"apple", "ball", "cat"}sorted_str_set = sorted(str_set, reverse=True) print(sorted_str_set) # ➜ ["cat", "ball", "apple"] sorted_by_length = sorted(str_set, key=len) print(sorted_by_length) # ➜ ["cat", "ball", "apple"] 📌 "cat" has 3 letters, "ball" has 4 letters, and "apple" has 5 letters.
    4.5 Copying Sets
    1. copy() creates a copy of a set. This is useful when we want to modify the copied set without changing the original set. Example: original_set = {1, 2, 3}copied_set = original_set.copy()copied_set.add(4)print(original_set) # ➜ {1, 2, 3} print(copied_set) # ➜ {1, 2, 3, 4}
    4.6 Assignment is Not Copy
    1. If we assign one set to another variable using =, both variables refer to the same set. Example: original_set = {1, 2, 3}same_set = original_setsame_set.add(4)print(original_set) # ➜ {1, 2, 3, 4} print(same_set) # ➜ {1, 2, 3, 4} 📌 Use copy() when you want a separate set.

5. 🔗 Set Operations

    5.1 What are Set Operations?
    1. Set operations are used to compare and combine groups of data. Common Set Operations: union() ➜ Combines all unique items intersection() ➜ Finds common items difference() ➜ Finds items present in one set but not another symmetric_difference() ➜ Finds items that are in either set, but not both
    5.2 union()
    1. union() combines all unique items from two sets. Symbol: |Example: set_a = {1, 2, 3} set_b = {3, 4, 5}print(set_a.union(set_b)) # ➜ {1, 2, 3, 4, 5} print(set_a | set_b) # ➜ {1, 2, 3, 4, 5}
    5.3 intersection()
    1. intersection() finds common items between two sets. Symbol: &Example: set_a = {1, 2, 3} set_b = {3, 4, 5}print(set_a.intersection(set_b)) # ➜ {3} print(set_a & set_b) # ➜ {3}
    5.4 difference()
    1. difference() finds items that are in the first set but not in the second set. Symbol: -Example: set_a = {1, 2, 3} set_b = {3, 4, 5}print(set_a.difference(set_b)) # ➜ {1, 2} print(set_a - set_b) # ➜ {1, 2} 📌 set_a - set_b is different from set_b - set_a.
    5.5 symmetric_difference()
    1. symmetric_difference() finds items that are in either set, but not in both. Symbol: ^Example: set_a = {1, 2, 3} set_b = {3, 4, 5}print(set_a.symmetric_difference(set_b)) # ➜ {1, 2, 4, 5} print(set_a ^ set_b) # ➜ {1, 2, 4, 5}

6. 🧊 Frozenset

    6.1 What is frozenset?
    1. frozenset is an immutable version of a set. Once created, items cannot be added or removed. Example: my_frozenset = frozenset([1, 2, 3]) print(my_frozenset) # ➜ frozenset({1, 2, 3})
    6.2 frozenset is Immutable
    1. Example: my_frozenset = frozenset([1, 2, 3]) my_frozenset.add(4) # ➜ AttributeError ⚠️ This line gives an error because frozenset does not have add(). 📌 AttributeError means Python does not allow that action on this data type because the tool or method is not available.

Practice QuestionsNot started

  1. 1. Creating and Checking Sets

    Question 1 of 6

      1.1 Practice creating and checking sets:
      1. Create a set named username_set with the values: "ram123", "sita45", "ram123", "hari88"
      2. Display username_set and observe duplicate values.
      3. Create an empty set named empty_set.
      4. Display the type of empty_set.
      5. Create a set with values 1, "hello", and (1, 2).
      6. Try to create a set with a list inside it and observe the error.
      7. Check whether "ram123" is present in username_set.
      8. Check whether "mohan22" is not present in username_set.
  2. 2. Adding and Removing Set Items

    Question 2 of 6

      2.1 Create unq_items_set = {"book", "pen", "pencil", "marker", "notebook"}
      1. Add "sticky_notes" to unq_items_set and display the updated set.
      2. Add "pen" again and observe the result.
      3. Create new_items = ["highlighter", "chart_paper"].
      4. Add all items from new_items to unq_items_set using update().
      5. Remove "pen" using remove() and display the updated set.
      6. Try to remove "eraser" using discard() and display the result.
      7. Remove one arbitrary item using pop().
      8. Display the removed item.
      9. Display the updated set.
  3. 3. Removing Duplicates

    Question 3 of 6

      3.1 Store this list: items_sold = ["book", "book", "pen", "pen", "pen", "pencil", "marker", "notebook"]
      1. Convert items_sold into a set named unq_items_set.
      2. Display all unique items sold in the stationery shop.
      3. Display total number of unique items sold.
      4. Sort unique items and display the result.
  4. 4. Set Operations with Movies

    Question 4 of 6

      4.1 Ask user for movies released in 2025 and store them as a set. Ask user again for movies watched by the user and store them as a set.
      1. Find movies released in 2025 that the user has watched.
      2. Find movies released in 2025 that the user has not watched.
      3. Find movies watched by the user that were not released in 2025.
  5. 5. Customer Category Analysis

    Question 5 of 6

      5.1 Electronic gadget top buyers are {"ram", "shyam", "sita", "hari"}, cosmetic top buyers are {"hari", "sita", "gita", "rita"}, grocery top buyers are {"ram", "hari", "gita", "rabi"}
      1. Find customers who are top buyers of all three categories.
      2. Find all unique customers who are top buyers of at least one category.
      3. Find customers who are top buyers of electronics but not cosmetics.
      4. Find customers who are top buyers of electronics and cosmetics.
      5. Find customers who are top buyers of cosmetics and groceries.
      6. Find customers who are top buyers of electronics and groceries.
      7. Find customers who are top buyers of exactly one category.
      8. Find customers who are top buyers of exactly two categories.
  6. 6. Frozenset Practice

    Question 6 of 6

      6.1 Practice working with frozenset:
      1. Create a frozenset from [1, 2, 3].
      2. Display the frozenset.
      3. Try to add 4 to the frozenset and observe the error.