Tuesday, August 26, 2025

๐ŸSETS IN PYTHON

Sets are unordered collections of unique items. They are useful for membership testing, removing duplicates, and performing mathematical set operations.

1) What is a Set?

A set is an unordered collection of unique elements enclosed in curly braces { } or created using set(). Sets do not allow duplicates and do not maintain order.


# Examples
empty_set = set()        # Note: {} creates an empty dictionary
numbers = {1, 2, 3, 4}
fruits = {"apple", "banana", "cherry"}
mixed = {1, "Alice", True}

2) Accessing Elements

Since sets are unordered, elements cannot be accessed by index. You can iterate through sets:


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

for fruit in fruits:
    print(fruit)

3) Adding and Removing Elements


fruits = {"apple", "banana"}

# Adding
fruits.add("cherry")
fruits.update(["mango", "kiwi"])  # Add multiple items

# Removing
fruits.remove("banana")  # Raises KeyError if item not found
fruits.discard("orange") # Does not raise error if item not found
popped_item = fruits.pop() # Removes a random item
fruits.clear()            # Remove all items

4) Set Operations

Python sets support mathematical operations like union, intersection, difference, and symmetric difference:


a = {1, 2, 3, 4}
b = {3, 4, 5, 6}

print(a | b)   # Union: {1, 2, 3, 4, 5, 6}
print(a & b)   # Intersection: {3, 4}
print(a - b)   # Difference: {1, 2}
print(a ^ b)   # Symmetric Difference: {1, 2, 5, 6}

5) Common Set Methods

  • add(x) – Add an element
  • update(iterable) – Add multiple elements
  • remove(x) – Remove element (KeyError if missing)
  • discard(x) – Remove element safely
  • pop() – Remove a random element
  • clear() – Remove all elements
  • union(), intersection(), difference(), symmetric_difference() – Mathematical operations

6) Common Mistakes

  • Using mutable elements like lists inside sets → TypeError
  • Expecting order → sets are unordered
  • Accessing by index → not allowed

๐Ÿ–ฅ️ Practice in Browser

No comments:

Post a Comment

๐ŸWhat is scikitlearn??