Python Program on Set Methods

Master Python with 70+ Hands-on Projects and Get Job-ready - Learn Python

In this article, we’ll explore two Python programs that delve into the world of sets, a powerful data structure in Python for handling unique elements. The first program focuses on various set operations, including union, clear, copy, pop, add, discard, and remove. The second program involves user input to create a set and then calculates the sum of its elements, showcasing the versatility of sets in Python.

Prerequisites

  • Basic understanding of sets and their properties in Python.
  • Familiarity with fundamental Python concepts, including variables, loops, and user input.
  • Knowledge of essential set methods such as clear(), union(), copy(), pop(), add(), discard(), and remove().

Topic Explanation

Program 1 – begins with the initialization of two sets, myset1 and myset2, followed by a series of set operations. These operations include clearing a set, performing a union with another set (myset2), creating a copy of a set, popping an element, adding an element, and attempting to discard and remove non-existent elements. The program demonstrates essential set functionalities in Python.

Code:

# Creating two sets, myset1 and myset2, with some initial values
myset1 = {10, 20, 30, 40, 50, 60, 800}
myset2 = {100, 20, 50, 10, 600}

# Printing the contents of myset1
print(myset1)

# Clearing all elements from myset1
myset1.clear()

# Printing the union of an empty set (myset1) and myset2
# Note: The result is the same as myset2 since myset1 is empty
print(myset1.union(myset2))

# Creating a copy of myset1 and assigning it to myset2
myset2 = myset1.copy()

# Checking if myset1 is empty before attempting to pop an element
if myset1:
    # Removing an arbitrary element from myset1 using pop()
    # Note: Since sets are unordered, the specific element popped is not predictable
    myset1.pop()
else:
    print("Cannot pop from an empty set")

# Printing the modified contents of myset1 after popping an element
print(myset1)

# Adding the element 100 to myset1
myset1.add(100)

# Discarding the element 500 from myset1 if it exists
# Note: discard() does not raise an error if the element is not present
myset1.discard(500)

# Attempting to remove the element 500 from myset1
# Note: remove() raises a KeyError if the element is not present
# In this case, a KeyError will be caught and a message will be printed
try:
    myset1.remove(500)
except KeyError:
    print("Element 500 not found in the set")

# Printing the final contents of myset1 after the above operations
# Note: The element 500 was not added back due to the remove() operation
print(myset1)

Output:

{800, 50, 20, 40, 10, 60, 30}
{50, 100, 20, 600, 10}
Cannot pop from an empty set
set()
Element 500 not found in the set
{100}

Code Explanation:

  • myset1 is defined as a set with the elements 10, 20, 30, 40, 50, 60, 800
  • myset2 is defined as a set with the elements 100, 20, 50, 10, 600
  • print(myset1) prints out the set myset1
  • myset1.clear() clears all elements in the set myset1
  • print(myset1.union(myset2)) prints the union of the (now empty) myset1 and myset2
  • myset2 is set to a copy of myset1, so it is now an empty set
  • print(myset2) prints the empty set myset2
  • myset1.pop() attempts to remove an element from the empty set myset1, so no change
  • myset1.add(100) adds the element 100 to myset1
  • myset1.discard(500) attempts to discard 500 from myset1, but does nothing since 500 is not in myset1
  • myset1.remove(500) would error since 500 is not in myset1 to remove
  • print(myset1) prints the set myset1, which contains only the element 100

Program 2 – involves user interaction to create a set. The user is prompted to enter the limit for the set, and then a loop captures user input to populate the set. Finally, the program calculates and prints the sum of the elements in the set, showcasing the simplicity and usefulness of sets for mathematical operations.

Code:

# Creating an empty set named 'myset' using the set() constructor.
myset = set({})

# Taking user input for the limit of elements to be added to the set.
n = int(input("Enter the limit: "))

# Prompting the user to enter elements for the set in a loop.
print("Enter elements in the set:")
for i in range(n):
    # Taking user input for each element and converting it to an integer.
    x = int(input())
    
    # Adding the entered element to the set 'myset'.
    myset.add(x)

# Printing the sum of the elements in the set 'myset'.
print("Sum of elements in the set:", sum(myset))

Output:

Enter the limit: 5
Enter elements in the set:
1
2
3
2
4
Sum of elements in the set: 10

Code Explanation:

  • myset is defined as an empty set using set() constructor
  • n takes user input for the limit of elements to add to the set
  • Print statement to prompt user to enter elements in the set
  • Loop runs from 0 to n-1 (where n is the user entered limit)
  • In each iteration, x takes the user input integer
  • Add x to myset using myset.add(x) to add element x to the set
  • Print the sum of all elements in myset using sum(myset) – sums all numerical elements in the set

Summary

In conclusion, this article offers a comprehensive exploration of sets in Python through two illustrative programs. The first program provides a detailed overview of fundamental set operations, offering insights into their behavior and showcasing how sets handle unique elements. The second program introduces user interaction, emphasizing the practical application of sets for collecting and processing user-inputted data, culminating in a calculation of the set’s element sum.

Through these examples, readers gain a deeper understanding of the versatility and efficiency of sets in Python, particularly for scenarios involving distinct elements and mathematical operations. The provided code explanations and output samples contribute to a clear and insightful learning experience, making this article valuable for Python developers seeking to enhance their proficiency with sets and foundational Python concepts. As readers engage with these programs, they not only grasp the mechanics of sets but also reinforce their knowledge of essential Python programming techniques.

Did you like this article? If Yes, please give DataFlair 5 Stars on Google

courses

DataFlair Team

DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.

Leave a Reply

Your email address will not be published. Required fields are marked *