Python From Beginner to Advanced

0% completed

Previous
Next
Python - set Operations

Sets in Python not only manage unique collections of items but also support various mathematical operations like union, intersection, and difference. These operations are useful for comparing sets and extracting relevant data based on these comparisons.

Union

The union of two sets is a set containing all elements from both sets, without duplicates. The union operation can be performed using the union() method or the | operator.

Example

Demonstrating the union of two sets.

Python3
Python3

. . . .

Explanation:

  • set1 and set2 contain overlapping and unique elements.
  • set1.union(set2) computes the union, resulting in {1, 2, 3, 4, 5}.
  • The | operator is an alternative that achieves the same result, showing the flexibility of set operations in Python.

Intersection

The intersection of two sets is a set containing only the elements that are common to both sets. The intersection operation can be performed using the intersection() method or the & operator.

Example

Demonstrating the intersection of two sets.

Python3
Python3

. . . .

Explanation:

  • set1.intersection(set2) computes the intersection, resulting in {2, 3}, which are the common elements in both sets.
  • The & operator provides a shorthand for the intersection method, yielding the same outcome.

Difference

The difference between two sets is a set containing elements that are in the first set but not in the second set. This operation helps in identifying unique elements in a set compared to another. The difference operation can be performed using the difference() method or the - operator.

Example

Demonstrating the difference between two sets.

Python3
Python3

. . . .

Explanation:

  • set1.difference(set2) calculates the difference, resulting in {1, 2}, which are the elements unique to set1 not found in set2.
  • The - operator is another way to express the difference, simplifying syntax while providing the same results.

These set operations are fundamental tools in Python for handling complex data relationships and analyses. By understanding how to perform unions, intersections, and differences, you can effectively manage and manipulate sets in your applications.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next