How do I create sets in Python for beginners?

In Python, a set is a collection that is unordered, mutable, and does not allow duplicate elements. Sets are useful when you need to store unique items and perform operations such as union, intersection, and difference. You can create a set by using curly braces or the `set()` function.

Creating Sets

Here are two common ways to create a set in Python:

  • Using curly braces:
my_set = {1, 2, 3, 4, 5}
  • Using the set() function:
  • my_set = set([1, 2, 3, 4, 5])

    Example:

    # Creating a set
    my_set = {1, 2, 3, 4, 5}
    
    # Adding an element
    my_set.add(6)
    
    # Removing an element
    my_set.remove(3)
    
    # Displaying the set
    print(my_set)  # Output: {1, 2, 4, 5, 6}
    

    Python Sets Creating Sets Unique Items Mutable Collections