Python set() Function



The Python set() function is used to create a new set. A set is a collection of unique elements, meaning that each item appears only once in the set.

It is an unordered and mutable (changeable) data structure that allows you to store different types of data, such as numbers, strings, or other objects. Sets are defined using curly braces {}, and the elements inside the set are separated by commas.

Syntax

Following is the syntax of Python set() function −

set(iterable)

Parameters

This function accepts any iterable object like a string, list, or another set as a parameter.

Return Value

This function returns a new set object with the unique elements from the given iterable.

Example

In the following example, we are using the set() function to convert the list "my_list" into a set by removing duplicate elements −

my_list = [1, 2, 2, 3, 4, 4]
set_from_list = set(my_list)
print('The set object obtained is:',set_from_list)

Output

Following is the output of the above code −

The set object obtained is: {1, 2, 3, 4}

Example

Here, we are using the set() function to convert the string "hello" into a set containing unique characters −

my_string = "hello"
set_from_string = set(my_string)
print('The set object obtained is:',set_from_string)

Output

Output of the above code is as follows −

The set object obtained is: {'l', 'e', 'h', 'o'}

Example

In here, we are using the set() function without any arguments, creating an empty set "(set())" −

empty_set = set()
print('The set object obtained is:',empty_set)

Output

The result obtained is as shown below −

The set object obtained is: set()

Example

In this case, we convert the elements of the tuple "(1, 2, 3, 3)" into a set by eliminating duplicate elements −

my_tuple = (1, 2, 3, 3)
set_from_tuple = set(my_tuple)
print('The set object obtained is:',set_from_tuple)

Output

Following is the output of the above code −

The set object obtained is: {1, 2, 3}

Example

In this example, we use the set() function to convert the list of words "word_list" into a set, ensuring that only unique words are retained −

word_list = ["apple", "banana", "apple", "orange"]
unique_words_set = set(word_list)
print('The set object obtained is:',unique_words_set)

Output

The result produced is as follows −

The set object obtained is: {'apple', 'banana', 'orange'}
python-set-function.htm
Advertisements