The set() function creates a set in Python.
Example
set() Syntax
The syntax of set() is:
set(iterable)
Recommended Reading: Python sets
set() Parameters
set() takes a single optional parameter:
- iterable (optional) - a sequence (string, tuple, etc.) or collection (set, dictionary, etc.) or an iterator object to be converted into a set.
set() Return Value
set() returns:
- an empty set if no parameters are passed
- a set constructed from the given iterable parameter
Example 1: Create sets from string, tuple, list, and range
Output
set()
{'P', 'o', 't', 'n', 'y', 'h'}
{'a', 'o', 'e', 'u', 'i'}
{'a', 'o', 'e', 'u', 'i'}
{0, 1, 2, 3, 4}
Note: We cannot create empty sets using { } syntax as it creates an empty dictionary. To create an empty set, we use set().
Example 2: Create sets from another set, dictionary and frozen set
Output
{'a', 'o', 'i', 'e', 'u'}
{'a', 'o', 'i', 'e', 'u'}
{'a', 'o', 'e', 'u', 'i'}
Example 3: Create set() for a custom iterable object
Output
{1, 2, 3, 4, 5}