Python set() Function

The set() function in Python is used when we need to create a set object. For example:

myset = set(('codes', 'cracker', 'dot', 'com'))

print(type(myset))
print(myset)

The output is:

<class 'set'>
{'cracker', 'com', 'dot', 'codes'}

Python set() Function Syntax

The syntax of set() function in Python, is:

set(iterable)

where iterable refers to a collection, a sequence, or an iterator object.

Note: If no parameter(s) is/are passed to set(), then an empty set will get returned by this function.

Python set() Function Example

Here is an example of set() function in Python:

s = set()
print(s)

x = [12, 4, 54]
s = set(x)
print(s)

x = (12, 32, 54, 65)
s = set(x)
print(s)

x = {"Day": "Sat", "Month": "Dec"}
s = set(x)
print(s)

The output is:

set()
{12, 4, 54}
{32, 65, 12, 54}
{'Day', 'Month'}

Note: If set is created from dictionary object, then the key will become the element of set.

Python Online Test


« Previous Function Next Function »