Python Sets

Python Set

A set in Python is an unordered collection of unique elements. Unlike lists or tuples, sets do not allow duplicate values and do not maintain order. They are highly useful when you need to ensure that only unique items are stored, and they support operations like union, intersection, and difference. Sets are determined by curly brackets { }

Example:

# Examples of set in Python
set1 = {} # An empty set
set2 = {4, 5, 1, 7, 3} # A set with 5 integers
set3 = {True, False, True, False, True} # A set with 5 boolean values
set4 = {1, ‘XYZ’, True} # In Python, different types of values can be stored in a set

Explanation:
● set1 = { }: This is an empty set that doesn’t contain any elements.
● set2 = {4, 5, 1, 7, 3}: This set contains 5 integer values: 4, 5, 1, 7, and 3.
● set3 = {True, False, True, False, True}: This set contains 5 boolean values: True, False, True, False, and True.
● set4 = {1, ‘XYZ, ‘True’}: This set contains 3 values of distinct data types. In python it is possible to store different types of values.

Creating and Accessing a Python set:
Scenario: Let’s create a set with the values {2, 4, 10, 5, 15, 3} and access the 3rd element using the set index.

Python-Set

# Create a set and access the 3rd element
numbers = {2, 4, 10, 5, 15, 3}
print(f”The third element: {numbers[2]}”)

Explanation:
● numbers = {2, 4, 10, 5, 15, 3}: This initializes a set with 6 integer values: 2, 4, 10, 5, 15, and 3.
● print(f”The third element: {numbers[2]}”): This prints the 3rd element of the set. In Python, sets are zero-indexed, meaning the index starts from 0. Therefore, numbers[2] refers to the 3rd element, which is 10.

Set Operations
1. Union: Combines elements from two sets, removing duplicates.

set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2)
print(union_set) # Output: {1, 2, 3, 4, 5}

2. Intersection: Returns elements common to both sets.

intersection_set = set1.intersection(set2)
print(intersection_set) # Output: {3}

3. Difference: Returns elements present in the first set but not in the second.

difference_set = set1.difference(set2)
print(difference_set) # Output: {1, 2}

4. Symmetric Difference: Returns elements in either set, but not in both.

symmetric_difference_set = set1.symmetric_difference(set2)
print(symmetric_difference_set) # Output: {1, 2, 4, 5}

Task:
1. Integer set:
Create a set of integers with values from 1 to 5.
Print all elements of the set.

2. String set:
Create a set of strings with the names of three fruits.
Print all elements of the set.

3. Double set:
Create a set of doubles with any 4 double values.
Print the sum of all elements in the set.

4. Boolean set:
Create a set of booleans with alternating true and false values.
Print all elements of the set.

Course Video

YouTube Reference :