DEV Community

Cover image for Python Sets
Narasimma Radhakrishnan
Narasimma Radhakrishnan

Posted on

Python Sets

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))
Enter fullscreen mode Exit fullscreen mode

Output

{10, 50, 20}
<class 'set'>
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Output

{'b', 'a', 'c'}
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Output

{'Geeks', 'for'}
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)