Set is a built-in Python data type used to store a collection of unique items.
Stores only unique elements; duplicate values are automatically removed.
Unordered collection, so elements do not have a fixed position and cannot be accessed using indexes.
Example: This example shows how to create a set with some numbers and check its type.
s = {10, 50, 20} print(s)Exa print(type(s)) Output
{10, 50, 20} <class 'set'> Type Casting
set() method is used to convert other data types, such as lists or tuples, into sets.
s = set(["a", "b", "c"]) print(s) Output
{'b', 'a', 'c'} Check unique and Immutable
Sets cannot have duplicate values. While you cannot modify the individual elements directly, you can still add or remove elements from the set.
# a set cannot have duplicate values s = {"Geeks", "for", "Geeks"} print(s) # values of a set cannot be changed s[1] = "Hello" print(s) Output
{'Geeks', 'for'} Operators for Sets
Sets and frozen sets support the following operators:
Operators Notes
key in s containment check
key not in s non-containment check
s1 == s2 s1 is equivalent to s2
s1 != s2 s1 is not equivalent to s2
s1 <= s2 s1 is subset of s2
s1 < s2 s1 is proper subset of s2
s1 >= s2 s1 is superset of s2
s1 > s2 s1 is proper superset of s2
s1 | s2 the union of s1 and s2
s1 & s2 the intersection of s1 and s2
s1 - s2 the set of elements in s1 but not s2
s1 ˆ s2 the set of elements in precisely one of s1 or s2
