Tuesday, January 7, 2025

Sets in Python Definition Characteristics Creating Duplicate Efficiency Exercise


  1. Definition of Sets

    • Sets are used to store multiple items in a single variable.
    • One of four built-in data types in Python for collections, alongside List, Tuple, and Dictionary.
  2. Characteristics of Sets

    • Unordered: Items do not have a defined order and appear in a random sequence.
    • Unchangeable: Items cannot be modified after creation, but items can be added or removed.
    • Unindexed: Items cannot be accessed via an index or key.
    • No Duplicates: Each item must be unique within the set.
  3. Creating a Set

    • Sets are defined using curly brackets ({}).
    • Example: myset = {"apple", "banana", "cherry"}.
    • Sets can also be created using the set() constructor.
  4. Duplicate Values

    • Sets do not allow duplicate values.
    • The values True and 1 are treated as duplicates.
    • The values False and 0 are treated as duplicates.
  5. Checking the Length

    • Use the len() function to determine the number of items in a set.
    • Example: len(myset).
  6. Data Types in Sets

    • Set items can be of any data type (e.g., strings, integers, booleans).
    • A set can contain mixed data types.
  7. Using the set() Constructor

    • Example: set(("apple", "banana", "cherry")) creates a set.
  8. Python Collections (Comparison)

    • List: Ordered, changeable, allows duplicates.
    • Tuple: Ordered, unchangeable, allows duplicates.
    • Set: Unordered, unchangeable, unindexed, no duplicates.
    • Dictionary: Ordered (Python 3.7+), changeable, no duplicates.
  9. Exercise

    • Example question: Which one is a set?
      • Correct answer: myset = {'apple', 'banana', 'cherry'}.
  10. Efficiency and Usefulness

    • Choosing the right collection type can improve efficiency, security, and retention of meaning.

💥 YouTube https://www.youtube.com/channel/UCJojbxGV0sfU1QPWhRxx4-A

💥 Blog https://localedxcelcambridgeictcomputerclass.blogspot.com/

1. Access Items in a Set

  • Indexing Not Allowed: Items in a set cannot be accessed using an index or a key.
  • Looping Through Items: You can loop through the set using a for loop.
    • Example:
      thisset = {"apple", "banana", "cherry"}
      for x in thisset:
          print(x)
      
  • Check for Item Presence: Use the in keyword to check if a value exists in the set.
    • Example:
      print("banana" in thisset)
      
  • Check for Item Absence: Use the not in keyword to check if a value does not exist in the set.
    • Example:
      print("banana" not in thisset)
      

2. Changing Items in a Set

  • Items Cannot Be Changed: Once a set is created, its items cannot be modified.
  • Adding New Items: You can add new items to a set.

These points summarize all key aspects of accessing and working with items in a set.

💥 YouTube https://www.youtube.com/channel/UCJojbxGV0sfU1QPWhRxx4-A

💥 Blog https://localedxcelcambridgeictcomputerclass.blogspot.com/

1. Adding Items to a Set

  • Items Cannot Be Changed: Once a set is created, its existing items cannot be modified.
  • Adding New Items: You can add new items to a set using the add() method.
    • Example:
      thisset = {"apple", "banana", "cherry"}
      thisset.add("orange")
      print(thisset)
      

2. Adding Items from Another Set

  • Use the update() Method: To add all items from one set to another, use the update() method.
    • Example:
      thisset = {"apple", "banana", "cherry"}
      tropical = {"pineapple", "mango", "papaya"}
      thisset.update(tropical)
      print(thisset)
      

3. Adding Any Iterable

  • Accepts Iterable Objects: The update() method can add items from any iterable object, such as tuples, lists, or dictionaries.
    • Example (Adding a List):
      thisset = {"apple", "banana", "cherry"}
      mylist = ["kiwi", "orange"]
      thisset.update(mylist)
      print(thisset)
      

4. Exercise

  • Correct Syntax for Adding Items:
    • Answer: add()

These points summarize how to add items to a set in Python.

--

Here is a list of all key points from the text:

1. Removing Items from a Set

  • Methods for Removing Items: Use the remove() or discard() methods.
    • Example (Using remove()):

      thisset = {"apple", "banana", "cherry"}
      thisset.remove("banana")
      print(thisset)
      

      Note: If the item does not exist, remove() will raise an error.

    • Example (Using discard()):

      thisset = {"apple", "banana", "cherry"}
      thisset.discard("banana")
      print(thisset)
      

      Note: If the item does not exist, discard() will NOT raise an error.

2. Removing a Random Item

  • Use the pop() Method: Removes a random item from the set.
    • Example:
      thisset = {"apple", "banana", "cherry"}
      x = thisset.pop()
      print(x)  # Removed item
      print(thisset)  # Remaining set
      
      Note: Since sets are unordered, you cannot predict which item will be removed.
      Return Value: The removed item is returned by the pop() method.

3. Clearing the Set

  • Use the clear() Method: Empties the set.
    • Example:
      thisset = {"apple", "banana", "cherry"}
      thisset.clear()
      print(thisset)  # Outputs: set()
      

4. Deleting the Set

  • Use the del Keyword: Deletes the set entirely.
    • Example:
      thisset = {"apple", "banana", "cherry"}
      del thisset
      # Accessing `thisset` after this will raise an error as it no longer exists.
      

5. Exercise

  • Correct Syntax for Removing an Item:
    • Answer: remove()

💥 YouTube https://www.youtube.com/channel/UCJojbxGV0sfU1QPWhRxx4-A

💥 Blog https://localedxcelcambridgeictcomputerclass.blogspot.com/

Here is a list of key points from the text:

1. Looping Through Set Items

  • Using a for Loop: You can iterate over items in a set using a for loop.
    • Example:
      thisset = {"apple", "banana", "cherry"}
      for x in thisset:
          print(x)
      
      Note: Since sets are unordered, the order of items in the loop is not guaranteed.

2. Exercise

  • Correct Syntax for Looping Through Set Items:
    • Answer:
      for x in {'apple', 'banana', 'cherry'}:
          print(x)
      

These points summarize how to loop through a set and identify the correct syntax for iterating over set items.

-------------

Python - Join Sets: Key Points


1. Joining Sets

  • union() method: Combines all items from both sets into a new set.
    • Example:
      set1 = {"a", "b", "c"}
      set2 = {1, 2, 3}
      set3 = set1.union(set2)
      print(set3)
      
  • | operator: An alternative to union() for joining sets.
    • Example:
      set3 = set1 | set2
      print(set3)
      

2. Joining Multiple Sets

  • Using union() method: Add multiple sets in parentheses separated by commas.
    • Example:
      myset = set1.union(set2, set3, set4)
      print(myset)
      
  • Using | operator: Separate multiple sets with additional | operators.
    • Example:
      myset = set1 | set2 | set3 | set4
      print(myset)
      

3. Joining a Set and Other Data Types

  • union() method: Allows joining sets with lists, tuples, etc., resulting in a set.
    • Example:
      x = {"a", "b", "c"}
      y = (1, 2, 3)
      z = x.union(y)
      print(z)
      
    • Note: The | operator works only with sets.

4. Updating Sets

  • update() method: Adds all items from one set to another and modifies the original set.
    • Example:
      set1 = {"a", "b", "c"}
      set2 = {1, 2, 3}
      set1.update(set2)
      print(set1)
      

5. Intersection of Sets

  • intersection() method: Returns a new set with only common items (duplicates) from both sets.
    • Example:
      set3 = set1.intersection(set2)
      print(set3)
      
  • & operator: Alternative to intersection().
    • Example:
      set3 = set1 & set2
      print(set3)
      
  • intersection_update() method: Keeps only duplicates in the original set.
    • Example:
      set1.intersection_update(set2)
      print(set1)
      

6. Difference of Sets

  • difference() method: Returns items from the first set not present in the second set.
    • Example:
      set3 = set1.difference(set2)
      print(set3)
      
  • - operator: Alternative to difference().
    • Example:
      set3 = set1 - set2
      print(set3)
      
  • difference_update() method: Modifies the original set to keep items not in the other set.
    • Example:
      set1.difference_update(set2)
      print(set1)
      

7. Symmetric Difference of Sets

  • symmetric_difference() method: Keeps all items except the duplicates from both sets.
    • Example:
      set3 = set1.symmetric_difference(set2)
      print(set3)
      
  • ^ operator: Alternative to symmetric_difference().
    • Example:
      set3 = set1 ^ set2
      print(set3)
      
  • symmetric_difference_update() method: Keeps all except duplicates in the original set.
    • Example:
      set1.symmetric_difference_update(set2)
      print(set1)
      

8. Special Cases

  • Duplicate Value Consideration:
    • True and 1 are considered the same value.
    • False and 0 are considered the same value.
    • Example:
      set1 = {"apple", 1, "banana", 0}
      set2 = {False, "google", 1, True}
      set3 = set1.intersection(set2)
      print(set3)
      

9. Exercise

  • Correct Syntax for Joining Sets:
    • Answer:
      set3 = set1.union(set2)
      

Set Methods and Descriptions

  1. add()
    Adds an element to the set.

  2. clear()
    Removes all the elements from the set.

  3. copy()
    Returns a copy of the set.

  4. difference() (-)
    Returns a set containing the difference between two or more sets.

  5. difference_update() (-=)
    Removes the items in this set that are also included in another, specified set.

  6. discard()
    Removes the specified item without raising an error if the item doesn't exist.

  7. intersection() (&)
    Returns a set that is the intersection of two other sets (common items).

  8. intersection_update() (&=)
    Removes the items in this set that are not present in other, specified set(s).

  9. isdisjoint()
    Returns whether two sets have no intersection (True if they share no elements).

  10. issubset() (<=)
    Returns whether all items in this set are present in another specified set.

  11. <
    Returns whether this set is a proper subset of another set.

  12. issuperset() (>=)
    Returns whether all items in another set are present in this set.

  13. >
    Returns whether this set is a proper superset of another set.

  14. pop()
    Removes and returns an arbitrary element from the set (raises an error if the set is empty).

  15. remove()
    Removes the specified element (raises an error if the element does not exist).

  16. symmetric_difference() (^)
    Returns a set with the symmetric differences of two sets (items not present in both sets).

  17. symmetric_difference_update() (^=)
    Updates the set with the symmetric differences of this set and another.

  18. union() (|)
    Returns a set containing the union of two or more sets (all unique elements from all sets).

  19. update() (|=)
    Updates the set with the union of this set and others (adds all items from the specified sets).

These methods provide a wide range of operations to manipulate and analyze sets in Python.


💥 YouTube https://www.youtube.com/channel/UCJojbxGV0sfU1QPWhRxx4-A

💥 Blog https://localedxcelcambridgeictcomputerclass.blogspot.com/

💥 WordPress https://computerclassinsrilanka.wordpress.com

💥 Facebook https://web.facebook.com/itclasssrilanka

💥 Wix https://itclasssl.wixsite.com/icttraining

💥 Web https://itclasssl.github.io/eTeacher/

💥 Medium https://medium.com/@itclasssl

💥 Quora https://www.quora.com/profile/BIT-UCSC-UoM-Final-Year-Student-Project-Guide

💥 mystrikingly https://bit-ucsc-uom-final-year-project-ideas-help-guide-php-class.mystrikingly.com/

💥 https://elakiri.com/threads/bit-ucsc-uom-php-mysql-project-guidance-and-individual-classes-in-colombo.1627048/

💥 https://bitbscucscuomfinalprojectclasslk.weebly.com/

💥 https://www.tiktok.com/@onlinelearningitclassso1

💥 https://payhip.com/eTeacherAmithafz/

💥 https://discord.gg/cPWAANKt