A set in Python is an unordered collection of unique items. It automatically removes duplicates and is very efficient for membership testing and mathematical set operations.
{} or set() to create sets.You can create sets using curly braces or the set() constructor. Duplicate values are automatically removed.
fruits = {"apple", "banana", "cherry"}
print(fruits) # {'banana', 'apple', 'cherry'}
numbers = set([1, 2, 3, 4])
print(numbers) # {1, 2, 3, 4}
fruits.add("orange")
fruits.update(["kiwi", "mango"])
print(fruits) # {'apple', 'banana', 'cherry', 'orange', 'kiwi', 'mango'}
fruits.remove("banana")
fruits.discard("pineapple") # no error
print(fruits) # {'apple', 'cherry', 'orange', 'kiwi', 'mango'}
Set operations don’t guarantee order, so printed results may vary. Duplicates are removed automatically, and using discard() avoids errors when the item does not exist.
if x in my_set.add() and update().remove() and discard().in operator.