Skip to main content

Python program for SET operations.

Description

This Python code illustrates the use of sets, which are unordered collections of unique elements that do not allow duplicates. It initializes a set of months, prints the original set, adds "July" and "August" to the set, and demonstrates that sets maintain uniqueness and handle duplicates.

Code

program5a.py
months=set(["January","February","March","April","May","June"])
print("The original set")
print(months)
print("Adding other months to the set")
months.add("July")
months.add("August")
print("printing modified set")
print(months)

Explanation of above code

  • Sets in Python are unordered collections of unique elements, and they do not allow duplicates.
  • Sets can be defined using curly braces or created using the set() constructor.
  • Set Initialization: The code begins by initializing a set named months using the set literal notation.
  • This set contains the names of six months: 'January,' 'February,' 'March,' 'April,' 'May,' and 'June.'
  • Sets automatically handle duplicates, ensuring that only one unique instance of each element is stored.
  • Printing the Original Set: The code uses the print function to display the original contents of the months set.
  • This illustrates the fact that sets are unordered collections, and the order in which elements are displayed may not match the order in which they were added.
  • Adding Elements to the Set: The code demonstrates how to add elements to the set by introducing 'July' and 'August' to the months set.
  • It uses the add method, which is specific to sets.
  • Sets ensure the uniqueness of elements, so attempting to add a duplicate value will be ignored.
  • Printing the Modified Set: After adding 'July' and 'August' to the set, the code prints the updated contents of the months set.
  • This demonstrates that the new elements, 'July' and 'August,' have been successfully included.
  • Sets maintain their uniqueness, guaranteeing that no duplicate elements exist within the set.
  • In summary, sets are a valuable data structure in Python, particularly when you need to store a collection of distinct and unique values. They are also useful for performing set operations such as union, intersection, and difference. This code exemplifies the simplicity and uniqueness of sets, showcasing their ability to store and manipulate collections of distinct elements.

Learn more

Reference