Set in Python

 


In Python, a set is an unordered collection of unique elements. Sets are similar to lists and tuples but with a key difference: sets do not allow duplicate values, and they are unordered, meaning they do not maintain the order of elements. Sets are also mutable, so you can add or remove elements.

Set Definition

A set is defined by placing elements inside curly braces {}, and the elements are separated by commas.

Syntax:

  • set_name = {item1, item2, item3, ...}


Creating a Set

  • # Example of a set with integers

  • numbers = {1, 2, 3, 4, 5}


  • # Example of a set with different data types

  • mixed_set = {1, "Python", 3.14, True}


  • # Creating an empty set

  • empty_set = set()


  • # Example of a set with duplicate elements (duplicates will be removed)

  • duplicate_set = {1, 2, 2, 3, 4, 4}

  • print(duplicate_set)


Output:

  • {1, 2, 3, 4}


As shown, the duplicates are removed when creating a set.

Accessing Set Elements

Unlike lists and tuples, you cannot access set elements using an index because sets are unordered. To iterate through a set, you must use a loop.

Example:

  • my_set = {1, 2, 3, 4, 5}

  • for item in my_set:

  •     print(item)


Output:

  • 1

  • 2

  • 3

  • 4

  • 5


The order of the elements when iterating through the set is not guaranteed.

Set Operations

Adding Elements

You can add elements to a set using the add() method.

  • my_set = {1, 2, 3}

  • my_set.add(4)  # Adds 4 to the set

  • print(my_set)


Output:

  • {1, 2, 3, 4}


Adding Multiple Elements

You can add multiple elements using the update() method, which accepts another iterable (like a list or tuple).

  • my_set = {1, 2, 3}

  • my_set.update([4, 5, 6])  # Adds 4, 5, 6 to the set

  • print(my_set)


Output:

  • {1, 2, 3, 4, 5, 6}


Removing Elements

You can remove an element from a set using the remove() or discard() methods. The remove() method will raise a KeyError if the element is not found, while discard() will not.

  • my_set = {1, 2, 3, 4, 5}


  • # remove() raises an error if element is not found

  • my_set.remove(3)

  • print(my_set)  # Output: {1, 2, 4, 5}


  • # discard() does not raise an error if element is not found

  • my_set.discard(6)  # 6 is not in the set, but no error occurs

  • print(my_set)  # Output: {1, 2, 4, 5}


You can also use the pop() method, which removes and returns an arbitrary element from the set.

  • my_set = {1, 2, 3, 4}

  • removed_element = my_set.pop()

  • print(removed_element)  # Output: Some random element

  • print(my_set)


Output:

  • 1

  • {2, 3, 4}


Clearing a Set

You can remove all elements from a set using the clear() method.

  • my_set = {1, 2, 3, 4, 5}

  • my_set.clear()

  • print(my_set)  # Output: set()


Set Operations

Python provides various set operations that are useful for performing mathematical set operations such as union, intersection, and difference.

Union of Sets (|)

The union of two sets combines all elements from both sets.

  • set1 = {1, 2, 3}

  • set2 = {3, 4, 5}

  • union_set = set1 | set2

  • print(union_set)


Output:

  • {1, 2, 3, 4, 5}


Intersection of Sets (&)

The intersection of two sets gives the common elements.

  • set1 = {1, 2, 3}

  • set2 = {3, 4, 5}

  • intersection_set = set1 & set2

  • print(intersection_set)


Output:

  • {3}


Difference of Sets (-)

The difference between two sets gives the elements that are in the first set but not in the second.

  • set1 = {1, 2, 3}

  • set2 = {3, 4, 5}

  • difference_set = set1 - set2

  • print(difference_set)


Output:

  • {1, 2}


Symmetric Difference (^)

The symmetric difference gives the elements that are in either set, but not in both.

  • set1 = {1, 2, 3}

  • set2 = {3, 4, 5}

  • symmetric_diff = set1 ^ set2

  • print(symmetric_diff)


Output:

  • {1, 2, 4, 5}


Subset (<=)

You can check if a set is a subset of another set using the <= operator or the issubset() method.

  • set1 = {1, 2, 3}

  • set2 = {1, 2, 3, 4, 5}

  • print(set1 <= set2)  # Output: True


Superset (>=)

You can check if a set is a superset of another set using the >= operator or the issuperset() method.

  • set1 = {1, 2, 3, 4, 5}

  • set2 = {1, 2, 3}

  • print(set1 >= set2)  # Output: True


Disjoint Sets

You can check if two sets are disjoint (i.e., they have no common elements) using the isdisjoint() method.

  • set1 = {1, 2, 3}

  • set2 = {4, 5, 6}

  • print(set1.isdisjoint(set2))  # Output: True


Set Comprehensions

Like list comprehensions, you can create sets using a set comprehension.

Syntax:

  • {expression for item in iterable if condition}


Example:

  • squares = {x**2 for x in range(5)}

  • print(squares)


Output:

  • {0, 1, 4, 9, 16}


Frozen Sets

A frozen set is an immutable version of a set. Once a frozen set is created, its elements cannot be modified.

Creating a Frozen Set:

  • frozen_set = frozenset([1, 2, 3, 4])

  • print(frozen_set)


Output:

  • frozenset({1, 2, 3, 4})


Frozen sets support methods like union(), intersection(), and difference(), but they do not support methods that modify the set, like add() or remove().

Use Cases for Sets

  • Removing Duplicates: Since sets do not allow duplicates, you can use them to remove duplicate items from a list.

  • Mathematical Set Operations: Sets are useful for performing operations like union, intersection, and difference, which are commonly used in mathematics, data analysis, and algorithms.

  • Membership Testing: Sets are optimized for fast membership testing, i.e., checking if an element is present in the set.

Conclusion:

  • Sets are unordered collections of unique elements in Python.

  • They provide various set operations like union, intersection, and difference, making them suitable for mathematical and data manipulation tasks.

  • Sets are mutable (you can add/remove elements), but they do not allow duplicate values and are unordered.

Let me know if you need further clarification or examples! 😊


Post a Comment

0 Comments