To initialize a set in Python, you can use curly braces notation or the set() constructor.
In this example,
my_set
.my_set
using curly braces notation {}
containing initial elements.my_set
using set operations such as adding elements, removing elements, and checking for membership.# Initialize a set with curly braces
my_set = {"apple", "banana", "orange"}
# my_set is now initialized with elements "apple", "banana", and "orange"
# Example usage:
# Add elements to the set
my_set.add("kiwi")
# Remove elements from the set
my_set.remove("banana")
# Check if an element is present in the set
contains_element = "apple" in my_set
print("Is element 'apple' present in the set:", contains_element)
Is element 'apple' present in the set: True
In this example,
set()
constructor without passing any arguments to create an empty set in Python.# Initialize an empty set with set() constructor
empty_set = set()
# empty_set is now initialized as an empty set
# Example usage:
# Add elements to the set
empty_set.add("apple")
# Remove elements from the set (if it exists)
empty_set.discard("apple")
# Check if an element is present in the set
contains_element = "apple" in empty_set
print("Is element 'apple' present in the set:", contains_element)
Is element 'apple' present in the set: False
In this tutorial, we learned How to Initialize a Set in Python language with well detailed examples.