search

What is the use of the "set" function in Python?

In Python, the set() function is used to create a set object. The set() function takes an iterable as an argument and returns a new set containing the unique elements from the iterable. Here are a few use cases of the set() function:

  1. Creating a Set from a List:
my_list = [1, 2, 3, 3, 4, 4, 5]
my_set = set(my_list)
print(my_set)  # Output: {1, 2, 3, 4, 5}

In this example, the set() function is used to create a new set my_set from a list my_list. The duplicate elements in the list are automatically removed, resulting in a set with unique elements.

  1. Creating an Empty Set:
empty_set = set()
print(empty_set)  # Output: set()

You can use the set() function without any arguments to create an empty set. This is equivalent to creating an empty set using curly braces .

  1. Converting Other Iterables to Sets:
my_tuple = (1, 2, 3, 3, 4, 4, 5)
my_set = set(my_tuple)
print(my_set)  # Output: {1, 2, 3, 4, 5}

The set() function can be used to convert other iterable objects, such as tuples, strings, or ranges, into sets.

  1. Removing Duplicates from a String:
my_string = "abracadabra"
unique_chars = set(my_string)
print(unique_chars)  # Output: {'r', 'a', 'b', 'c', 'd'}

In this example, the set() function is used to create a set of unique characters from a string. The duplicate characters in the string are automatically eliminated, leaving only the unique characters in the resulting set.

The set() function is a convenient way to create sets and remove duplicates from iterables. It provides a simple and efficient approach to work with unique elements in Python.

Related Questions You Might Be Interested