Python set() Method

The set() is a constructor method that returns an object of the set class from the specified iterable and its elements. A set object is an unordered collection of distinct hashable objects. It cannot contain duplicate values.

Syntax:

set(iterable)

Parameters:

iterable: (Optional) An iterable such as string, list, set, dict, tuple or custom iterable class.

Return Value:

Returns a set object.

The following example converts different iterable types into a set with distinct elements.

Example: Convert List, Tuple, Dictionary, String to Set
numbers_list = [1, 2, 3, 4, 5, 5, 3, 2]
print("Converting list into set: ", set(numbers_list))

numbers_tuple = (1, 2, 3, 4, 5, 5, 4, 3)
print("Converting tuple into set: ", set(numbers_tuple))

numbers_dict = {1:'one',2:'two',3:'three'}
print("Converting dictionary into set: ", set(numbers_dict))

mystr = 'Hello World'
print("Converting string into set: ", set(numbers_string))
Output
Converting list into set:  {1, 2, 3, 4, 5}
Converting tuple into set:  {1, 2, 3, 4, 5}
Converting dictionary into set:  {1, 2, 3}
Converting string into set:  {'H', 'o', 'W', 'd', ' ', 'l', 'e', 'r'}