The set()
function in Python is a built-in function that creates a set object, which is an unordered collection of unique elements. Sets are mutable and can contain various data types like integers, strings, and tuples. When passed an iterable as an argument, set()
converts the elements to a set, removing duplicates in the process.
Return Values
The set()
function in Python returns a new set object, which is a mutable collection of unique elements.
How to Use set()
in Python
The set()
function creates a set object from the given iterable object such as a list or a tuple. It removes duplicates and returns a collection of unique elements.
data = [1, 2, 3, 3, 4, 5]
unique_set = set(data)
print(unique_set) # Output: {1, 2, 3, 4, 5}
Using set()
with a string will create a set of unique characters in the string.
text = 'hello'
unique_chars = set(text)
print(unique_chars) # Output: {'h', 'e', 'l', 'o'}
The set()
function can also be used to convert a dictionary's keys to a set to get unique keys.
data = {'a': 1, 'b': 2, 'c': 3}
unique_keys = set(data)
print(unique_keys) # Output: {'a', 'b', 'c'}