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 the 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 be returned by this function.

Python set() function example

Here is an example of the 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 a dictionary object, then the key will become an element of set.

Advantages of the set() function in Python

Disadvantages of the set() function in Python

Python Online Test


« Previous Function Next Function »


Liked this post? Share it!