set() function in Python is used to create a set, which is an unordered collection of unique elements. It removes duplicate values automatically and accepts an iterable such as a list, tuple, string, range or dictionary.
Example: In this example, set() is used to create a set from a list containing duplicate values.
a = [1, 2, 2, 3]
s = set(a)
print(s)
Output
{1, 2, 3}
Explanation: set(a) converts the list a into a set and duplicate value 2 is removed automatically.
Syntax
set(iterable)
- Parameters: iterable (optional) - An iterable like list, tuple, string, range or dictionary. If not provided, it creates an empty set.
- Returns: Returns a new set with unique elements.
Examples
Example 1: In this example, an empty set is created using set(). This is useful when elements need to be added later.
a = set()
print(a)
print(type(a))
Output
set() <class 'set'>
Explanation: set() creates an empty set and type(s) confirms the object is a set.
Example 2: In this example, a list with duplicate values is converted into a set. This removes all repeated elements.
a = [4, 5, 5, 6, 7]
s = set(a)
print(s)
Output
{4, 5, 6, 7}
Explanation: set(a) removes duplicate value 5 and only unique elements remain.
Example 3: In this example, a tuple is converted into a set. Duplicate values are removed automatically.
t = (1, 1, 2, 3)
s = set(t)
print(s)
Output
{1, 2, 3}
Explanation: set(t) converts tuple t into a set, duplicate value 1 is removed.
Example 4: In this example, range() is used with set() to create a set of numbers.
s = set(range(3, 8))
print(s)
Output
{3, 4, 5, 6, 7}
Explanation: set(range(3, 8)) creates a set from numbers generated by range().
Example 5: In this example, a dictionary is passed to set(). Only dictionary keys are included in the set.
d = {'x': 1, 'y': 2, 'z': 3}
s = set(d)
print(s)
Output
{'x', 'z', 'y'}
Explanation: set(d) takes only the keys from dictionary d, values are not included.