Extra 5% OFF Use Code: OL05
Free Shipping over ₹999

Sets

A set in Python is an unordered, mutable, and unindexed collection of unique elements. It is useful when you need to store multiple items without duplicates and perform set operations like union, intersection, and difference.

1. Creating a Set

A set is defined using curly braces {} or the set() function.

# Creating a set
fruits = {"apple", "banana", "cherry"}
print(fruits)  # Output: {'banana', 'cherry', 'apple'}

# Using set() function
numbers = set([1, 2, 3, 4, 5])
print(numbers)  # Output: {1, 2, 3, 4, 5}

Key Points:

  • Sets do not allow duplicate values.
  • The order of elements is not guaranteed (unordered).
  • Sets do not support indexing (no set[0]).

2. Adding Elements to a Set

You can add elements using add() (for a single element) and update() (for multiple elements).

# Adding a single element
fruits.add("orange")
print(fruits)  # Output: {'banana', 'cherry', 'apple', 'orange'}

# Adding multiple elements
fruits.update(["grape", "mango"])
print(fruits)  # Output: {'banana', 'cherry', 'apple', 'orange', 'grape', 'mango'}

3. Removing Elements from a Set

You can remove elements using remove(), discard(), or pop().

# Removing a specific element (raises an error if not found)
fruits.remove("banana")
print(fruits)  # Output: {'cherry', 'apple', 'orange', 'grape', 'mango'}

# Using discard() (no error if element is missing)
fruits.discard("grape")
print(fruits)  # Output: {'cherry', 'apple', 'orange', 'mango'}

# Using pop() (removes a random element)
removed_element = fruits.pop()
print(fruits)  # Output: Set without one random element
print("Removed:", removed_element)

Note:

  • remove() raises an error if the element doesn’t exist.
  • discard() does not raise an error.
  • pop() removes a random element.

4. Checking Membership in a Set

Use in and not in to check if an item exists in a set.

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

print("apple" in fruits)   # Output: True
print("grape" not in fruits)  # Output: True

5. Set Operations

Python sets support operations like union, intersection, difference, and symmetric difference.

OperationMethodSymbolDescription
Unionset1.union(set2)`set1set2`
Intersectionset1.intersection(set2)set1 & set2Common elements in both sets
Differenceset1.difference(set2)set1 - set2Elements in set1 but not in set2
Symmetric Differenceset1.symmetric_difference(set2)set1 ^ set2Elements in either set1 or set2, but not both

Example:

A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}

print(A | B)  # Union → {1, 2, 3, 4, 5, 6, 7, 8}
print(A & B)  # Intersection → {4, 5}
print(A - B)  # Difference → {1, 2, 3}
print(A ^ B)  # Symmetric Difference → {1, 2, 3, 6, 7, 8}

6. Set Methods

MethodDescription
add(x)Adds x to the set
update(iterable)Adds multiple elements
remove(x)Removes x (error if missing)
discard(x)Removes x (no error if missing)
pop()Removes a random element
clear()Removes all elements
union(set2)Combines two sets
intersection(set2)Finds common elements
difference(set2)Elements in set1 but not set2
symmetric_difference(set2)Elements in set1 or set2, but not both
issubset(set2)Checks if set1 is a subset of set2
issuperset(set2)Checks if set1 is a superset of set2

7. Subsets & Supers

A = {1, 2, 3}
B = {1, 2, 3, 4, 5}

print(A.issubset(B))  # True (A is a subset of B)
print(B.issuperset(A))  # True (B is a superset of A)

8. Frozen Sets (Immutable Sets)

A frozen set is an immutable version of a set.

frozen_set = frozenset([1, 2, 3, 4])
# frozen_set.add(5)  #  TypeError: 'frozenset' object has no attribute 'add'
print(frozen_set)  # Output: frozenset({1, 2, 3, 4})

    Leave a Reply

    Your email address will not be published.

    Need Help?