In Python, the set() function is a built-in function used to create a set object. A set is an unordered collection of unique elements. The set() function can be used to convert other data types such as lists, tuples, and strings into sets.
The basic syntax for the set() function is as follows:
|
set(iterable)
|
where iterable is a sequence of elements to be converted into a set. If iterable is not provided, an empty set will be created.
Here are some examples of using the set() function:
Example 1: Creating an empty set
|
my_set = set()
print(my_set)
|
Output:
set()In this example, an empty set is created using the set() function, and then printed to the console.
Example 2: Creating a set from a list
|
my_list = [1, 2, 2, 3, 4, 4, 5]
my_set = set(my_list)
print(my_set)
|
Output:
{1, 2, 3, 4, 5}
In this example, a list of integers is created and assigned to the variable my_list. The set() function is then used to convert my_list into a set. Since sets can only contain unique elements, the duplicate elements in my_list are automatically removed when it is converted into a set.
Example 3: Creating a set from a string
|
my_string = "hello"
my_set = set(my_string)
print(my_set)
|
Output:
{'h', 'e', 'l', 'o'}
In this example, a string of characters is created and assigned to the variable my_string. The set() function is then used to convert my_string into a set. Since sets can only contain unique elements, each character in my_string is automatically added to the set.
Example 4: Creating a set from a tuple
|
my_tuple = (1, 2, 2, 3, 4, 4, 5)
my_set = set(my_tuple)
print(my_set)
|
Output:
{1, 2, 3, 4, 5}In this example, a tuple of integers is created and assigned to the variable my_tuple. The set() function is then used to convert my_tuple into a set. Since sets can only contain unique elements, the duplicate elements in my_tuple are automatically removed when it is converted into a set.
In conclusion, the set() function is a useful tool in Python for creating sets from other data types such as lists, tuples, and strings. The set() function can be called on any iterable object in Python, and it automatically removes duplicate elements and creates an unordered collection of unique elements.