11.1.Set Examples
11.1.Set Examples
Example-1: Write a program to remove the given number from the set?
my_set = {1,2,3,4,5,6,12,24}
n = int(input("Enter the number you want to remove"))
my_set.discard(n)
print("After Removing:",my_set)
Output: Enter the number you want to remove:12
After Removing: {1, 2, 3, 4, 5, 6, 24}
a = set([3,2,1])
a
Output: {1, 2, 3}
>>> a = {10,20}a.issubset(a)
True
5. Check if a specific value exists in a set
Like other types of iterables, we can check if a value exists in a set with the in operator.
>>> s = {5,7,9}5 in s
True
>>> 6 in s
False
7. Write a Python program to create a set with elements "apple", "banana", and "cherry".
>>> fruits = {"apple", "banana", "cherry"}
20. Write a Python program to remove and return an arbitrary element from a set.
>>> my_set = {1,2,6,4,5}
>>> my_set.pop()
1
21. Write a Python program to find the maximum and minimum elements in a set.
>>> my_set = {2,6,4,5}
>>> max(my_set)
6
>>> min(my_set)
2
22. Write a Python program to find the difference between two sets using the '-' operator.
>>> set1 = {1, 2, 3}
>>> set2 = {3, 4, 5}
>>> difference_set = set1 - set2
>>> difference_set
{1, 2}
23. Write a Python program to update a set with elements from another iterable.
>>> my_set = {2, 4, 5, 6}
>>> new_elements = [6, 7, 8]
>>> my_set.update(new_elements)
>>> my_set
{2, 4, 5, 6, 7, 8}
24. Write a Python program to remove a specific element from a set using the discard
method.
>>> my_set = {2, 4, 5, 6, 7, 8}
>>> my_set.discard(6)
>>> my_set
{2,4,5,7,8}
25. Write a Python program to find the common elements between multiple sets.
>>> set1 = {1, 2, 3}
>>> set2 = {3, 4, 5}
>>> common_elements = set.intersection(set1, set2)
>>> common_elements
{3}
26. Write a Python program to remove the intersection of two sets from one set.
>>> set1 = {1, 2, 3}
>>> set2 = {3, 4, 5}
>>> set1.difference_update(set2)
{1, 2}