Python Sets and Set Operations

Python Sets and Set Operations

Python Sets and Set Operations

Sets are unordered collections in Python that do not allow duplicate elements. Let's explore sets and common set operations:

1. Creating Sets

Sets are created using curly braces `{}` or the `set()` constructor.


# Example
my_set = {1, 2, 3, 4, 5}
        

2. Common Set Operations

Python supports various set operations, including union, intersection, and difference.


# Example
set1 = {1, 2, 3, 4, 5}
set2 = {3, 4, 5, 6, 7}

union_set = set1 | set2  # Union
intersection_set = set1 & set2  # Intersection
difference_set = set1 - set2  # Difference
        

3. Modifying Sets

Sets are mutable, allowing the addition and removal of elements.


# Example
my_set.add(6)  # Adding an element
my_set.remove(3)  # Removing an element
        
Python Sets and Set Operations Python Sets and Set Operations Reviewed by Naveen Gupta on 1:13 AM Rating: 5

No comments:

Theme images by mammamaart. Powered by Blogger.