{"@context":"https://schema.org","@type":"Article","mainEntityOfPage":{"@type":"WebPage","@id":"https://www.tutorialsteacher.com/python/set-method"},"headline":"Python set() Method","author":{"@type":"Organization","name":"TutorialsTeacher","url":"https://www.tutorialsteacher.com/aboutus"},"publisher":{"@type":"Organization","name":"TutorialsTeacher","logo":{"@type":"ImageObject","url":"https://www.tutorialsteacher.com/Content/images/logo.svg"},"sameAs":["https://www.facebook.com/tutorialsteacher","https://twitter.com/tutorialstchr","https://www.youtube.com/@tutorialsteacherOfficial"]},"dateModified":"2021-06-26T15:03:44.2269796Z","description":"The set() is a constructor method that returns an object of the set class from the specified iterable and its elements."}set class from the specified iterable and its elements." />

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'}
Want to check how much you know Python?